douglascrockford/JSON-js — Issue #25: Extended years Date.prototype.toJSON
Author: petermichaux
Created: 2012-01-29 17:45:02+00:00
State: open

The Date.prototype.toJSON polyfill included in json2.js does not appear to allow for the correct required ability of representing extended years as described in 15.9.1.15.1 of the ECMAScript 5.1 specification and ISO 8601 4.1.3.3. The ISO document shows that years must be padded with zeros in the extended format.

function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}

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;
};

(new Date(-62198755200000)).toJSON()

The above produces "-1-01-01T00:00:00Z" but should produce "-000001-01-01T00:00:00Z"

There is an example of padding correctly in the es5-shim

https://github.com/kriskowal/es5-shim/blob/master/es5-shim.js#L860