Jörg B. Jörg B. - 3 months ago 18
C# Question

DateTime TryParseExact not parsing similar string?

I have a problem parsing a string representation of a DateTime value back into a DateTime instance using the DateTime.ParseExact(..) method.

For some reason using similar formatted strings (or maybe I am blind) with different values works for value A) and doesn't another time for value b) and I must be missing something here.. but I just can't find it:

var d1 = "14/10/2013 2:16:18 PM";
var d2 = "27/08/2016 12:20:34 PM";

var dFormat = "dd/MM/yyyy H:mm:ss tt";

DateTime dt = DateTime.MinValue; // out value for .TryParseExact(..)
var tryParseResultD1 = DateTime.TryParseExact(d1, dFormat, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AssumeUniversal, out dt);
var tryParseResultD2 = DateTime.TryParseExact(d2, dFormat, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AssumeUniversal, out dt);

tryParseResultD1.Dump(); // << returns False
tryParseResultD2.Dump(); // << returns True


.. for some reason trying to parse the 'd1' string doesn't work but parsing 'd2' does and I don't know why.

Does anyone know or see what's going on here?

Answer

You should change H for h.

h represents The hour, using a 12-hour clock from 1 to 12.

H represents The hour, using a 24-hour clock from 0 to 23.

In your case you want a 12 hour clock from 1 to 12:

var dFormat = "dd/MM/yyyy h:mm:ss tt";