Javascript Date.tojson Don't Get The Timezone Offset
Solution 1:
Date objects in ECMAScript are internally UTC. The timezone offset is used for local times.
The specification for Date.prototype.toJSON says that it uses Date.prototype.toISOString, which states that "the timezone is always UTC". What your solution is doing is offsetting the UTC time value of the date object by the timezone offset.
Consider adding your own method to Date.prototype, e.g.
Date.prototype.toJSONLocal = function() {
functionaddZ(n) {
return (n<10? '0' : '') + n;
}
returnthis.getFullYear() + '-' +
addZ(this.getMonth() + 1) + '-' +
addZ(this.getDate());
}
Edit
If you want to squeeze extra performance, the following should be faster:
Date.prototype.toJSONLocal = (function() {
functionaddZ(n) {
return (n<10? '0' : '') + n;
}
returnfunction() {
returnthis.getFullYear() + '-' +
addZ(this.getMonth() + 1) + '-' +
addZ(this.getDate());
};
}())
But that smacks of premature optimisation, so unless you are calling it thousands of times in a very short period, I wouldn't bother.
Solution 2:
I haven't noticed that the toJSON method don't take into account your timezone offset
But it does, it converts the local-time to Zulu (look at the end of the string: Z)
newDate( "2012-01-02T03:04:05+02:00" ).toJSON()
"2012-01-02T01:04:05.000Z"
Post a Comment for "Javascript Date.tojson Don't Get The Timezone Offset"