简体   繁体   中英

C# date time to listbox

I have a server with a .txt file. The program is saving the page to a textfile and then it is being processed per line using count. I then need to add it to datetime and then add it to a list.

So far it is pretty good except that last part datetime and the list. I always get format exception. I have tried a few variations of try parse and parse without luck.

The times are in a list like so:

 06:06 AM
 06:07
 12:12 
 12:50 

One per line

Message box shows each result at a time with no error and correct infomation.

while ((line = file.ReadLine()) != null)
{

  //  MessageBox.Show(line);
      List<DateTime> Busarrivetime = new List<DateTime>();
  //  DateTime tryme = DateTime.Parse(line, CultureInfo.InvariantCulture);
  //  MessageBox.Show(tryme.ToString());
      DateTime date;
      Busarrivetime.Add(date = DateTime.ParseExact(line,"hh:mm tt", System.Globalization.CultureInfo.InvariantCulture)); // ERRORS ON THIS LINE

      count++;
}

file.Close();

Console.ReadLine();

Exact error:

An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll

Here is the list I am working with .

Your time formats are not consistently same. For example 06:06 AM has am/pm designator where as 12:12 doesn't.

So consider using multiple possible formats.

DateTime.ParseExact(item, new[] { "hh:mm tt", "HH:mm" }, System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None);

This should work

Its a simple solution

I tested with this DateTime.ParseExact("06:06 AM ", "hh:mm tt", System.Globalization.CultureInfo.InvariantCulture);

and got an exception same as yours.

but tested with this

DateTime.ParseExact("06:06 AM", "hh:mm tt", System.Globalization.CultureInfo.InvariantCulture);

Did not get. File is picking up trailing or leading whitespace.

Use .Trim() function :) to remove them and then test

DateTime.ParseExact(("06:06 AM ").Trim(), "hh:mm tt", System.Globalization.CultureInfo.InvariantCulture);

Could it just be that there is an extra blank line at the end of the file?

// add this just inside your while loop
if (String.IsNullOrWhiteSpace(line))
    continue;

Also, you need to declare your list before the while loop, or you will just be getting a new list for each row instead of adding to one big list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM