【问题标题】:js can't add timezone offset to '1900-01-01T00:00:00'?js 无法将时区偏移量添加到“1900-01-01T00:00:00”?
【发布时间】:2017-06-05 02:19:31
【问题描述】:

我尝试new Date()获取UTC当地时间,

但现在 js 无法添加时区偏移量(例如,为中国添加 8 小时)。

在它正常工作之前。

在博客On the nightmare that is JSON Dates. Plus, JSON.NET and ASP.NET Web API

具有 ISO 8601 日期格式的 WebAPI json 结果是 '2017-05-10T07:50:16'.

【问题讨论】:

  • 关于您的编辑,JSON.NET 和 Web API 使用的 ISO 8601 日期格式包括为 UTC 添加的 Zin JSON.NET's documentation"2012-03-19T07:22Z" 有一个例子。
  • @JonathanLonowski 谢谢,我刚刚发现 [timeago](timeago.yarp.com) jquery 插件在 chrome 58 中无法正常工作。

标签: javascript google-chrome date asp.net-web-api2


【解决方案1】:

您需要在字符串中包含时区信息。

对于 UTC,可以用Z 表示。

new Date("2017-05-10T07:50:16Z").toUTCString()
// Wed, 10 May 2017 07:50:16 GMT

行为的变化反映了标准的变化。

  • 2011, 5th edition(你熟悉和期待的行为)

    缺席时区偏移的值为“Z”。

  • 2015, 6th edition

    如果不存在时区偏移,则日期时间被解释为本地时间。

  • 2016, 7th edition(当前行为)

    当不存在时区偏移时,仅日期形式被解释为 UTC 时间,日期时间形式被解释为本地时间

【讨论】:

  • 谢谢,也许这是 webAPI v2 的新错误。
【解决方案2】:

更改默认DatetimeConverter

 IsoDateTimeConverter converter = new IsoDateTimeConverter
        {
            DateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"
        };

config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(converter);

How to get JSON.NET to serialize date/time to ISO 8601?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-17
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 2016-04-28
    • 2022-07-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多