RHP RHP - 25 days ago 19
C# Question

DateTime.ParseExact Incorrect Format Specifier

The following code

var test = "2016-10-26_02-48-17-PM";
var testTime = DateTime.ParseExact(test, "yyyy-MM-dd_HH-mm-ss-tt", System.Globalization.CultureInfo.InvariantCulture);


throws the exception


An unhandled exception of type 'System.FormatException' occurred in
mscorlib.dll

Additional information: String was not recognized as a valid DateTime.


when executed. What did I miss?

Answer

You're mixing the 24 hour hour specifier "HH" with the AM/PM string "tt".

If you have your time in 24 hour clock format (00 - 23) then you don't need the AM/PM designation. However, if your times are 12 hour format with AM/PM you'll need to use the "hh" hour specifier.

This:

var test = "2016-10-26_02-48-17";
var testTime = DateTime.ParseExact(test, "yyyy-MM-dd_HH-mm-ss", System.Globalization.CultureInfo.InvariantCulture);

or this:

var test = "2016-10-26_02-48-17-PM";
var testTime = DateTime.ParseExact(test, "yyyy-MM-dd_hh-mm-ss-tt", System.Globalization.CultureInfo.InvariantCulture);

should work

Comments