I have to parse DateTime
objects from strings with the yyyyMMddhhmmss
format.
If I run this code, it works fine:
DateTime y = new DateTime(2013, 07, 22, 15, 35, 23);
string x = y.ToString("yyyyMMddhhmmss", CultureInfo.InvariantCulture);
But if I run this code - seemingly the inverse operation - I get an exception:
string x = "20130722153523";
DateTime y = DateTime.ParseExact(x, "yyyyMMddhhmmss", CultureInfo.InvariantCulture);
The exception is:
System.FormatException: String was not recognized as a valid DateTime.
I'm stumped as to what's wrong here. What am I doing wrong?
Note: Don't worry about timezones. I can deal with getting the correct timezone later.
The problem is that the date-time format you specified uses hh
for a 12-hour time format, but the input string has 15
in that area. It can't parse this because 15 is outside the expected range.
Try using HH
for a 24-hour time format instead:
string x = "20130722153523";
DateTime y = DateTime.ParseExact(x, "yyyyMMddHHmmss", CultureInfo.InvariantCulture);
Further Reading:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With