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 に答える