And*_*кин 26

在大多数较新的浏览器中,您有.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;
}
Run Code Online (Sandbox Code Playgroud)

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

  • 像这样你将覆盖ECMA Script 5方法,也适用于[支持它的浏览器](http://kangax.github.com/es5-compat-table/).请添加条件. (2认同)

Bea*_*rtz 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';
    };
}
Run Code Online (Sandbox Code Playgroud)