Discrepancy in JSON.stringify of date values in different browsers

前端 未结 4 513
忘掉有多难
忘掉有多难 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条回答
  •  猫巷女王i
    2020-12-31 05:20

    I got this working adding the following javascript:

    // Added to make dates format to ISO8601
    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())   + '.' +
             f(this.getUTCMilliseconds())   + 'Z';
    };
    

    I'm sure this probably slows down the serialization, but it seems to make things consistent across browsers.

提交回复
热议问题