anon
anon

Reputation:

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?

Upvotes: 1

Views: 54

Answers (2)

Martin
Martin

Reputation: 16423

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";

Upvotes: 3

Albert Hoekstra
Albert Hoekstra

Reputation: 128

Can you try to change the H for h in the format var dFormat?

If I'm correct h stands for 12 hour notation and H for 24 hour.

Upvotes: 0

Related Questions