Search code examples
c#datetimestring-to-datetime

DateTime.ParseExact throwing exception


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.


Solution

  • 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.