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 support older browsers without JSON.stringify(). I also have jquery-1.3.2.js included. I believe in newer browsers with native JSON support, it just passes through to the native JSON feature.
Here's the results I get in different browsers:
IE 8 on Windows XP: "2010-02-07T21:39:32Z"
Chrome 4.0 on Windows XP: "2010-02-07T21:39:59Z"
Firefox 3.0 of Windows XP: "2010-02-07T21:40:41Z"
Chrome 4.0 on Ubuntu linux: "2010-02-07T21:41:49Z"
Firefox 3.0 on Ubuntu linux: "2010-02-07T21:42:44Z"
Chrome 4.0 on Mac OSX: "2010-02-07T21:43:56Z"
Safari on Mac OSX: "2010-02-07T21:45:21Z"
Firefox 3.5 on Mac OSX: "2010-02-07T21:44:10.101Z"
Notice the last one? It contains milliseconds, and none of the others do. I don't have FF3.5 installed on any other systems, but I'm assuming they would have the same results.
Is there something I can do to make all dates on all platforms stringify the same? My backend REST service can be configured with a format string to deserialize JSON dates, but it can't support multiple formats, just one.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With