DateTime.ParseExact not working at all, why?

William Calleja picture William Calleja · Nov 16, 2010 · Viewed 10.6k times · Source

I am attempting to parse the following String into a DateTime object in c#:

DateTime.ParseExact("20101108 230125", "yyyyMMdd hhmmss", null)

although the value looks correct the ParseExact method just keeps giving me the following:

String was not recognized as a valid DateTime.

Can anybody tell me why and how I can parse the above string without having to do it the manual way? Isn't ParseExact supposed to be for this kind of occasion?

Answer

Fredrik Mörk picture Fredrik Mörk · Nov 16, 2010

You got the format for hours wrong, should be uppercase:

DateTime.ParseExact("20101108 230125","yyyyMMdd HHmmss", null)

Lowercase hh specifies that the time uses a 12-hour clock (with AM/PM). Uppercase HH is a 24 hour clock time.

For detailed info, check the documentation of custom DateTime format strings.