c# - 将 ISO 8601 日期时间字符串反序列化为 C# DateTime

标签 c# json.net

我正在尝试使用:

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/

相关文章:

c# - 为 HttpClient 中的 Get 操作显式设置内容类型 header

c# - 如何解决现有的两个 JSON.net 的冲突?

c# - Newtonsoft JSON 反序列化问题 [将值转换为类型时出错]

c# - IgnoreDataMember 不起作用,但 JsonIgnore 起作用

c# - 未触发 KeyDown 事件

c# - 有没有办法在特定时间显示表单

c# - 在网格行中查找控件

c# - bool 字段在反序列化后总是返回 false (Newtonsoft)

c# - 如何使用 Json.Net 将所有空值序列化为空字符串

c# - 在 C# 中减去 UTC 和非 UTC 日期时间