Parsing ISO 8601 string to DateTime in .NET? [duplicate]

不想你离开。 提交于 2019-11-26 21:53:11

问题


This question already has an answer here:

  • How to create a .NET DateTime from ISO 8601 format 7 answers

I have a string, "2009-10-08 08:22:02Z", which is in ISO 8601 format.

How do I use DateTime to parse this format?


回答1:


string txt= "2009-10-08 08:22:02Z";
DateTime output = DateTime.ParseExact(txt, "u", System.Globalization.CultureInfo.InvariantCulture);

The DateTime class supports the standard format string of u for this format

I think for the ISO format (with the T separator), use "s" instead of "u". Or use:

string txt= "2009-10-08 08:22:02Z";
DateTime output = DateTime.ParseExact(txt, new string[] {"s", "u"}, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);

to support both formats.




回答2:


No, it's not ISO 8601. Valid ISO 8601 representation would have T between time and date parts.

DateTime can natively handle valid ISO 8601 formats. However, if you're stuck with this particular representation, you can try DateTime.ParseExact and supply a format string.



来源:https://stackoverflow.com/questions/1536633/parsing-iso-8601-string-to-datetime-in-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!