Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can’t DateTime.ParseExact() parse the AM/PM in “4/4/2010 4:20:00 PM” using “M'/'d'/'yyyy H':'mm':'ss' 'tt”

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!

like image 712
Jimmy Avatar asked Apr 08 '10 01:04

Jimmy


1 Answers

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.

like image 159
Andrew Hare Avatar answered Sep 18 '22 15:09

Andrew Hare