Deserialize ISO 8601 date time string to C# DateTime

拟墨画扇 提交于 2020-01-14 09:08:33

问题


I'm trying to use:

JsonConvert.DeserializeObject<DateTime>( "2009-02-15T00:00:00Z", new IsoDateTimeConverter() )

But it gives me a FormatException: Input string was not in a correct format.

What am I doing wrong?


回答1:


If you're parsing a single value, the simplest approach is probably to just use DateTime.ParseExact:

DateTime value = DateTime.ParseExact(text, "o", null);

The "o" pattern is the round-trip pattern, which is designed to be ISO-8601:

The "O" or "o" standard format specifier corresponds to the "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK" custom format string for DateTime values and to the "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffzzz" custom format string for DateTimeOffset values.

I haven't specified a format provider, as it doesn't matter:

The pattern for this specifier reflects a defined standard (ISO 8601). Therefore, it is always the same regardless of the culture used or the format provider supplied.

If you need Json.NET to handle this transparently while deserializing other values, it may be a trickier proposition - others may know more.

Additionally, just as a plug, you may wish to consider using my Noda Time project, which supports ISO-8601 and integrates with JSON.NET - albeit not in a pre-packaged way just yet.



来源:https://stackoverflow.com/questions/17301229/deserialize-iso-8601-date-time-string-to-c-sharp-datetime

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