18

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.

Liam
  • 27,717
  • 28
  • 128
  • 190
barakcaf
  • 1,294
  • 2
  • 16
  • 27

4 Answers4

38

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.

Complexity
  • 5,682
  • 6
  • 41
  • 84
10

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.

Lloyd
  • 29,197
  • 4
  • 84
  • 98
2

Try This,

DateTime.ParseExact("2/22/2015 9:54:02 PM", "M/dd/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
itzmebibin
  • 9,199
  • 8
  • 48
  • 62
0

try this:

if (date.Contains("AM") || date.Contains("PM"))
    return DateTime.ParseExact(date, "dd.MM.yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
return DateTime.ParseExact(date, "dd.MM.yyyy HH:mm:ss", CultureInfo.InvariantCulture);
Ali Faradjpour
  • 302
  • 6
  • 15