Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a string containing AM/PM to DateTime?

Tags:

c#

How can i parse a string like this: "2/22/2015 9:54:02 AM" to a DateTime instance?

i am currently using the DateTime.ParseExact method but without the AM/PM i.e:

 DateTime.ParseExact("2/22/2015 9:54:02", "M/dd/yyyy HH:mm:ss")

I would like to be able to parse the AM/PM signs as well.

like image 289
barakcaf Avatar asked Feb 23 '15 10:02

barakcaf


1 Answers

You should change the hour format (H) to lowercase like this:

DateTime.ParseExact("2/22/2015 9:54:02 AM", "M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);

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

like image 51
Complexity Avatar answered Sep 28 '22 17:09

Complexity