将普通日期转换为ISO-8601格式

11

尽量不要丢失时区信息。请参见https://dev59.com/k3E85IYBdhLWcg3w3Xhp#15302113 - Daniel F
2个回答

28

在大多数新版浏览器中,你可以使用.toISOString()方法,但在IE8或更早版本中,你可以使用以下方法(取自Douglas Crockford的json2.js):

// Override only if native toISOString is not defined
if (!Date.prototype.toISOString) {
    // Here we rely on JSON serialization for dates because it matches 
    // the ISO standard. However, we check if JSON serializer is present 
    // on a page and define our own .toJSON method only if necessary
    if (!Date.prototype.toJSON) {
        Date.prototype.toJSON = function (key) {
            function f(n) {
                // Format integers to have at least two digits.
                return n < 10 ? '0' + n : n;
            }

            return this.getUTCFullYear()   + '-' +
                f(this.getUTCMonth() + 1) + '-' +
                f(this.getUTCDate())      + 'T' +
                f(this.getUTCHours())     + ':' +
                f(this.getUTCMinutes())   + ':' +
                f(this.getUTCSeconds())   + 'Z';
        };
    }

    Date.prototype.toISOString = Date.prototype.toJSON;
}

现在您可以安全地调用`.toISOString()`方法。

2
这样做会覆盖ECMA Script 5方法,包括browser that support it。请添加一个条件。 - Beat Richartz
很好的发现,@BeatRichartz!我已经相应地更新了我的答案。 - Andrei Андрей Листочкин
1
通常情况下,没有理由删除时区信息。请参见https://dev59.com/k3E85IYBdhLWcg3w3Xhp#15302113。 - Daniel F

6

日期对象上有.toISOString()方法。对于支持ECMA-Script 5的浏览器,您可以使用该方法。对于不支持的浏览器,可以按照以下方式安装该方法:

if (!Date.prototype.toISOString) {
    Date.prototype.toISOString = function() {
        function pad(n) { return n < 10 ? '0' + n : n };
        return this.getUTCFullYear() + '-'
            + pad(this.getUTCMonth() + 1) + '-'
            + pad(this.getUTCDate()) + 'T'
            + pad(this.getUTCHours()) + ':'
            + pad(this.getUTCMinutes()) + ':'
            + pad(this.getUTCSeconds()) + 'Z';
    };
}

你可以重新缩进下那段代码吗? - Bergi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接