parseexact
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);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);
Important Notes:
重要笔记:
HH means 24 hour time, hh means 12 hour time.
HH表示24小时, hh表示12小时。
- 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. 不要在一位数字一天的一位数字的早晨进行所有测试。 除夕晚上11:59是一个重要的测试案例。
- If I'd have tested with 01:01:01 then using lower case h's would have worked, but would have broken this afternoon. 如果我已经用01:01:01进行了测试,那么使用小写字母h可以奏效,但今天下午就坏了。
zzz means TimeZone offset like -07:00
zzz表示TimeZone偏移量,例如-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. 当执行ParseExact,然后使用相同格式的字符串与ToString往返时,将不会导致相同的字符串。
That means that:
这意味着:
DateTime foo = DateTime.ParseExact(poo,"yyyy-MM-ddTHH:mm:ss.fffffffzzz", System.Globalization.CultureInfo.InvariantCulture);
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"
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.
但是,DateTime的语义是相同的。
fffffff means 7 digits of fractional seconds
fffffff表示7位小数秒
T (in this context) has no specific meaning (it’s not reserved) so it is treated as a literal.
T (在这种情况下)没有特定含义(不是保留的),因此将其视为文字。
- System.Globalization.CultureInfo.InvariantCulture is almost always necessary when you’re working in a non-UI context. 在非UI上下文中工作时,几乎总是需要System.Globalization.CultureInfo.InvariantCulture。
- Don't get screwed when your application doesn't work when installed on an international version of Windows. 在国际版本的Windows上安装应用程序后,当您的应用程序无法运行时,请不要搞砸。
翻译自: https://www.hanselman.com/blog/dateparseexact-and-the-subtle-goo-that-is-datetime-format-strings
parseexact