6

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?

Mark Hurd
  • 10,175
  • 10
  • 62
  • 96
William Calleja
  • 3,716
  • 11
  • 39
  • 46

2 Answers2

20

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.

Fredrik Mörk
  • 147,210
  • 26
  • 277
  • 333
  • Why does this cause an exception? Personally I would expect hh to convert 23 into 11 rather than throw an exception. Is it ParseExact that causes it? – Marcus L Nov 16 '10 at 09:48
  • 1
    @Marcus: `ParseExact` will do what it says; parse the the string using the *exact* format specified. Since `hh` tells it to expect a 12-hour clock time value in that position, `23` clearly falls outside of the range of acceptable values. It parses the exact string, no conversions are made. So yes, the exception is thrown by the `ParseExact` method. – Fredrik Mörk Nov 16 '10 at 10:01
  • Cheers for the extended explanation. :) – Marcus L Nov 16 '10 at 10:13
2

Try using:

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

The "hh" is for 12 hour time and "HH" for 24 hour.

Richard Smith
  • 529
  • 6
  • 14