如何在JavaScript中使用ISO 8601格式化带有时区偏移的日期? [英] How to ISO 8601 format a Date with Timezone Offset in JavaScript?

查看:217
本文介绍了如何在JavaScript中使用ISO 8601格式化带有时区偏移的日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目标:查找本地时间 UTC时间偏移量然后构建网址格式如下。

Goal: Find the local time and UTC time offset then construct the URL in following format.

示例网址:/ Actions / Sleep?duration = 2002-10-10T12:00:00-05:00

Example URL: /Actions/Sleep?duration=2002-10-10T12:00:00−05:00

该格式基于W3C建议:
http://www.w3.org/TR/xmlschema11-2/#dateTime

The format is based on the W3C recommendation: http://www.w3.org/TR/xmlschema11-2/#dateTime

文档说:

 For example, 2002-10-10T12:00:00−05:00 (noon on 10 October 2002, 
Central Daylight Savings Time as well as Eastern Standard Time in the U.S.) 
is equal to 2002-10-10T17:00:00Z, five hours later than 2002-10-10T12:00:00Z.

所以根据我的理解,我需要通过新的Date()找到我的本地时间然后使用getTimezoneOffset ()函数计算差异然后将其附加到字符串的结尾。

So based on my understanding, I need to find my local time by new Date() then use getTimezoneOffset() function to compute the difference then attach it to the end of string.

1.以格式获取当地时间

1.Get local time with format

var local = new Date().format("yyyy-MM-ddThh:mm:ss"); //today (local time)

输出

2013-07-02T09:00:00

2.以小时为单位获取UTC时间偏移

2.Get UTC time offset by hour

var offset = local.getTimezoneOffset() / 60;

输出

7

3.Construct URL(仅限时间部分)

3.Construct URL (time part only)

var duration = local + "-" + offset + ":00";

输出

2013-07-02T09:00:00-7:00

以上输出结果表示我当地时间是2013/07/02 9am,与UTC的差异是7小时(UTC比当地时间早7小时)

The above output means my local time is 2013/07/02 9am and difference from UTC is 7 hours (UTC is 7 hours ahead of local time)

到目前为止它似乎工作,但如果getTimezoneOffset()返回负值如-120?

So far it seems to work but what if getTimezoneOffset() returns negative value like -120?

我想知道格式应该如何喜欢在这种情况下,因为我无法从W3C文件中弄清楚。在此先感谢。

I'm wondering how the format should look like in such case because I cannot figure out from W3C document. Thanks in advance.

推荐答案

以下内容应该正常,适用于所有浏览器(感谢@MattJohnson的提示)

The below should work properly, and for all browsers (thanks to @MattJohnson for the tip)

Date.prototype.toIsoString = function() {
    var tzo = -this.getTimezoneOffset(),
        dif = tzo >= 0 ? '+' : '-',
        pad = function(num) {
            var norm = Math.floor(Math.abs(num));
            return (norm < 10 ? '0' : '') + norm;
        };
    return this.getFullYear() +
        '-' + pad(this.getMonth() + 1) +
        '-' + pad(this.getDate()) +
        'T' + pad(this.getHours()) +
        ':' + pad(this.getMinutes()) +
        ':' + pad(this.getSeconds()) +
        dif + pad(tzo / 60) +
        ':' + pad(tzo % 60);
}

var dt = new Date();
console.log(dt.toIsoString());

这篇关于如何在JavaScript中使用ISO 8601格式化带有时区偏移的日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆