Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing Custom DateTime Format

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.

like image 226
Timothy Shields Avatar asked Jul 22 '13 20:07

Timothy Shields


1 Answers

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:

  • Custom Date and Time Format Strings
like image 175
p.s.w.g Avatar answered Nov 09 '22 21:11

p.s.w.g