【问题标题】:How do I get ISO8601 string with time offset in JavaScript?如何在 JavaScript 中获取带有时间偏移的 ISO8601 字符串?
【发布时间】:2015-10-13 09:27:01
【问题描述】:

我想得到一个时间字符串

"%Y%m-%dT%H:%M:%S%z"

使用 JavaScript 在 chrome 中格式化。但是 chrome 只返回 'Z' 字符,如下所示。

new Date().toISOString()
->"2015-07-23T07:41:36.617Z"

虽然我知道上面的结果是有效的,但我的项目还包括一个 c++ 应用程序。所以我想统一如下的日期格式。

2015-07-23T16:41:36.617+09:00

那么有什么好的方法可以实现我的日期格式吗?

ES6 规范

http://www.ecma-international.org/ecma-262/6.0/#sec-date-time-string-format

【问题讨论】:

标签: javascript date iso8601


【解决方案1】:

那么有什么好的方法可以实现我的日期格式吗?

如果您想要具有偏移量的本地时间 ISO-8601 版本,您所能做的就是使用getDaygetMonth 等的非 UTC 版本,从 getTimezoneOffset 获取时区偏移量,然后自己构建字符串。 (或者使用 MomentJS 之类的库。)规范中没有任何内容可以做到这一点。

【讨论】:

    【解决方案2】:

    是否有好的方法取决于。事实上,没有内置的方法可以做到这一点。但是你可以通过使用Date.getTimezoneOffset() 和做一些modulus 自己构建一个。这是一条线索:

    // set up date 2009-02-13T23:31:30.123Z (equivalent to 1234567890123 milliseconds):
    var localDate = new Date(1234567890123);
    // get local time offset, like -120 minutes for CEST (UTC+02:00):
    var offsetUTC = new Date().getTimezoneOffset();
    // set date to local time:
    localDate.setMinutes(localDate.getMinutes() - offsetUTC);
    offsetUTC = {
        // positive sign unless offset is at least -00:30 minutes:
        "s": offsetUTC < 30 ? '+' : '-',
        // local time offset in unsigned hours:
        "h": Math.floor(Math.abs(offsetUTC) / 60),
        // local time offset minutes in unsigned integers:
        "m": ~~Math.abs(offsetUTC) % 60
    };
    offsetUTC = offsetUTC.s + // explicit offset sign
                // unsigned hours in HH, dividing colon:
                ('0'+Math.abs(offsetUTC.h)+':').slice(-3) +
                // minutes are represented as either 00 or 30:
                ('0'+(offsetUTC.m < 30 ? 0 : 30)).slice(-2);
    
    localDate = localDate.toISOString().replace('Z',offsetUTC);
    // === "2009-02-13T23:31:30.123+02:00" (if your timezone is CEST)
         
    

    或者不那么冗长:

    localDate = localDate.toISOString().replace('Z',(offsetUTC<30?'+':'-')+
                ('0'+Math.floor(Math.abs(offsetUTC)/60)+':').slice(-3)+
                ('0'+((~~Math.abs(offsetUTC)%60)<30?0:30)).slice(-2));
    

    请注意……

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多