将ISO 8601日期时间字符串解串为C#DateTime [英] Deserialize ISO 8601 date time string to C# DateTime
问题描述
我试图使用方法:
JsonConvert.DeserializeObject<DateTime>( "2009-02-15T00:00:00Z", new IsoDateTimeConverter() )
但它给了我一个 FormatException:输入字符串的不正确的格式。
我在做什么错了?
推荐答案
如果你解析一个值,最简单的方法可能是只是使用的 DateTime.ParseExact
:
If you're parsing a single value, the simplest approach is probably to just use DateTime.ParseExact
:
DateTime value = DateTime.ParseExact(text, "o", null);
的
O模式是的往返模式的,其目的是通过ISO-8601:
The "o" pattern is the round-trip pattern, which is designed to be ISO-8601:
在O或O的标准格式说明对应于YYYY' - 'MM' - 'dd'T'HH':'毫米':'SS fffffffK'。自定义格式字符串DateTime值,并以YYYY' - 'MM' - 'dd'T'HH'。'':'毫米'SS fffffffzzz。自定义格式字符串的DateTimeOffset值
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:
这说明该模式反映了定义的标准(ISO 8601)。因此,它总是无论相同使用的培养物或所提供的格式提供的。
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.
如果您需要Json.NET透明地处理这一反序列化等价值,它可能是一个棘手的命题 - 其他人可能会知道更多。
If you need Json.NET to handle this transparently while deserializing other values, it may be a trickier proposition - others may know more.
此外,就像一个插件,您不妨考虑使用我的野田时间的项目,这支持ISO-8601和带JSON.NET集成 - 尽管不是在一个预先包装的方式,只是还没有
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.
这篇关于将ISO 8601日期时间字符串解串为C#DateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!