Date.ParseExact and the subtle goo that is DateTime Format Strings
We recently needed to parse this evil.
string poop = "2005-12-14T14:35:32.1700000-07:00";
DateTime poo = DateTime.ParseExact(poop,"yyyy-MM-ddTHH:mm:ss.fffffffzzz", System.Globalization.CultureInfo.InvariantCulture);
- HH means 24 hour time, hh means 12 hour time.
- Don't do all your testing in the morning of a one digit month on a one digit day. 11:59pm on New Years Eve is an important test case.
- If I'd have tested with 01:01:01 then using lower case h's would have worked, but would have broken this afternoon.
- zzz means TimeZone offset like -07:00
- When doing a ParseExact and then round-tripping with a ToString using the same format string will NOT result in the same string.
- That means that:
DateTime foo = DateTime.ParseExact(poo,"yyyy-MM-ddTHH:mm:ss.fffffffzzz", System.Globalization.CultureInfo.InvariantCulture);
foo.ToString("yyyy-MM-ddTHH:mm:ss.fffffffzzz") == "2005-12-14T13:35:32.1700000-08:00"
However, the semantics of the DateTime is the same.
- fffffff means 7 digits of fractional seconds
- T (in this context) has no specific meaning (it’s not reserved) so it is treated as a literal.
- System.Globalization.CultureInfo.InvariantCulture is almost always necessary when you’re working in a non-UI context.
- Don't get screwed when your application doesn't work when installed on an international version of Windows.