38

I'm using c#, and if I do

DateTime.ParseExact("4/4/2010 4:20:00 PM", "M'/'d'/'yyyy H':'mm':'ss' 'tt", null)

The return value is always 4:20 AM -- what am I doing wrong with using tt?

Thanks!

Andrew Hare
  • 344,730
  • 71
  • 640
  • 635
Jimmy
  • 5,131
  • 9
  • 55
  • 81
  • 1
    Several right answers... since I can only choose one right answer, I assume I should pick the first one to be submitted? – Jimmy Apr 08 '10 at 01:56

3 Answers3

77

Make the hour format (H) lowercase like this:

DateTime.ParseExact(
            "4/4/2010 4:20:00 PM", 
            "M/d/yyyy h:mm:ss tt", 
            CultureInfo.InvariantCulture);

Uppercase "H" indicates 24-hour time and lowercase "h" indicates 12-hour time and will respect the AM/PM in the candidate string.

Side note: It is best to provide an instance of IFormatProvider to methods like this (even if it's just CultureInfo.InvariantCulture). It's one of those things that doesn't really matter until you hit problems with it so it can be good to be in the habit of specifying culture information.

Andrew Hare
  • 344,730
  • 71
  • 640
  • 635
  • Thanks for the side note! I discussed this in another one of my questions: @Jimmy: It depends on the intent. In this case, / is used as an exact slash and not as a culture-sensitive separator (even when the culture is InvariantCulture), so the option that better expresses your intent is the one with quoted slashes (the one you picked) - http://stackoverflow.com/questions/1368636/why-cant-datetime-parseexact-parse-9-1-2009-using-m-d-yyyy . At the time I agreed with his conclusion (i.e., use '/' and null for the culture, rather than use CultureInfo.InvariantCulture). What do you think? – Jimmy Apr 08 '10 at 01:54
  • Great! It was the CultureInfo.InvariantCulture missing in my case, casue I had a lowercase 'h' and it still didn't parse! – edosoft Dec 24 '10 at 11:41
3

Try the following:

Console.WriteLine(DateTime.ParseExact("4/4/2010 4:20:00 PM", "M'/'d'/'yyyy h':'mm':'ss tt", null));

This outputs:

 4/4/2010 4:20:00 PM
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
2

You need to use a lowercase "h" for the hour argument in the format string. The uppercase "H" represents 24-hour time, so "4" is recognized as 4 AM (since "16" would be 4 PM).

DateTime.ParseExact("4/4/2010 4:20:00 PM", "M/d/yyyy h:mm:ss:tt", null)
Sean Carpenter
  • 7,681
  • 3
  • 37
  • 38