user2818430 user2818430 - 4 years ago 140
C# Question

ParseExact DateTime error

I have a list of DateTime as strings: dd.MM.yyyy H:mm:ss (The time is 24 hours format but the hour is single digit:

instead of

  • 14.12.2016 6:20:21

  • 15.12.2016 8:30:00

  • 16.12.2016 12:30:00

  • 17.12.2016 14:33:00

  • 18.12.2016 18:10:00

I am trying to parse exact the string values as a DateTime object like this:

DateTime.ParseExact(dt, "dd.MM.yyyy H:mm:ss", CultureInfo.InvariantCulture)
(dt is the string value from the list)

The problem is I get an error saying the string is not a valid DateTime ...

With the current format, the first and second values in the list work fine, when it get's to the third 'boooom' I get the error.

Am I missing something in my format?

Answer Source

Use the overload of DateTime.ParseExact that accepts an array of valid formats:

string[] formats = { "dd.MM.yyyy H:mm:ss", "dd.MM.yyyy HH:mm:ss" };
var result = DateTime.ParseExact(dt, formats, CultureInfo.InvariantCulture, 0);

UPDATE: As others have noted, H should match both one-digit and two-digit hours, so something else is going on. The following code runs successfully on my system (.NET 4.5.2):

string dt = "16.12.2016 12:30:00";
var result = DateTime.ParseExact(dt, "dd.MM.yyyy H:mm:ss", CultureInfo.InvariantCulture);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download