11

可能重复:
如何在 Javascript 中输出 ISO-8601 格式的字符串?

我有一个约会

Thu Jul 12 2012 01:20:46 GMT+0530

我怎样才能将它转换成这样的 ISO-8601 格式

2012-07-12T01:20:46Z
4

2 回答 2

27

在大多数较新的浏览器中,您都有.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() 方法。

于 2012-07-11T20:08:36.103 回答
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';
    };
}
于 2012-07-11T20:07:00.247 回答