0

I'm pretty sure that I am making some very stupid error but this is driving me insane.

I am trying to do the following:

var dateTime = DateTime.ParseExact("08/24/2016 12:00:00 AM", "MM/dd/yyyy HH:mm:ss tt", CultureInfo.InvariantCulture);

But I keep getting the following exception: "String was not recognized as a valid DateTime."

I have tried: "M/dd/yyyy HH:mm:ss tt" "MM'/'dd'/'yyyy HH:mm:ss tt" "M'/'dd'/'yyyy HH:mm:ss tt"

But nothing working so far... Any help would be appreciated.

Talon
  • 3,466
  • 3
  • 32
  • 47

3 Answers3

7

HH is looking for a 24 hour format, but you're also passing in AM and specifying tt - the parser can't deal with that. You need to either look for a 12-hour based string:

var dateTime = DateTime.ParseExact("08/24/2016 12:00:00 AM", "MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);

using hh, or remove the AM/tt part.

James Thorpe
  • 31,411
  • 5
  • 72
  • 93
2

Use hh for 12 hour format instead of HH for 24 hour format. This information is already in AM/PM and can't be handled twice by the method.

var dateTime = DateTime.ParseExact("08/24/2016 12:00:00 AM", "MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
fubo
  • 44,811
  • 17
  • 103
  • 137
1

You need to use hh instead of HH because HH is used for 24 hour format and you are also specifying am pm in format

var dateTime = DateTime.ParseExact("08/24/2016 12:00:00 AM", "MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
Mairaj Ahmad
  • 14,434
  • 2
  • 26
  • 40