How to convert a string containing AM/PM to DateTime?
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.
You can use the tt
specifier:
DateTime.ParseExact(
"2/22/2015 9:54:02 PM",
"M/dd/yyyy h:mm:ss tt",
CultureInfo.InvariantCulture
)
However be warned this can be locale specific. Also HH
refers to the 24 hour clock, with AM/PM you generally use the 12 hour clock, so you'd want to use hh
or just h
for that.