Discrepancy in JSON.stringify of date values in different browsers

前端 未结 4 425
忘掉有多难
忘掉有多难 2020-12-31 04:41

I have this code in an HTML page:

alert(JSON.stringify(new Date()));

I\'m including the latest json2.js (2009-09-29 version) in my page to

4条回答
  •  有刺的猬
    2020-12-31 05:13

    You could also adjust json2.js a bit to always use its own Date.prototype.toJSON instead of a possible native one. Here I uncommented two lines and it works correctly:

    // if (typeof Date.prototype.toJSON !== 'function') {
    
        Date.prototype.toJSON = function (key) {
    
            return isFinite(this.valueOf()) ?
                   this.getUTCFullYear()   + '-' +
                 f(this.getUTCMonth() + 1) + '-' +
                 f(this.getUTCDate())      + 'T' +
                 f(this.getUTCHours())     + ':' +
                 f(this.getUTCMinutes())   + ':' +
                 f(this.getUTCSeconds())   + 'Z' : null;
        };
    
        String.prototype.toJSON =
        Number.prototype.toJSON =
        Boolean.prototype.toJSON = function (key) {
            return this.valueOf();
        };
    // }
    

提交回复
热议问题