我正在尝试使用:
JsonConvert.DeserializeObject<DateTime>( "2009-02-15T00:00:00Z", new IsoDateTimeConverter() )
但它给了我一个FormatException: Input string was not in a correct format.
我做错了什么?
最佳答案
如果您要解析单个值,最简单的方法可能就是使用 DateTime.ParseExact
:
DateTime value = DateTime.ParseExact(text, "o", null);
“o”模式是 round-trip pattern ,其设计为 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.
我没有指定格式提供程序,因为这无关紧要:
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 在反序列化其他值的同时透明地处理此问题,这可能是一个更棘手的提议 - 其他人可能知道更多。
另外,作为一个插件,你不妨考虑使用我的Noda Time项目,它支持 ISO-8601 并与 JSON.NET 集成——尽管目前还没有以预打包的方式。
关于c# - 将 ISO 8601 日期时间字符串反序列化为 C# DateTime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17301229/