Skip to content Skip to sidebar Skip to footer

JavaScript Date.toJSON() Produces A Date Which Has Wrong Hours And Minutes

I want to print a Date to ISO-8601 standard: YYYY-MM-DDTHH:mm:ss.sssZ so I used the following lines of code, but I am getting unexpected output var date = new Date(2012, 10, 30, 6,

Solution 1:

var date = new Date();
console.log(date.toJSON(), new Date(date.getTime() - (date.getTimezoneOffset() * 60000)).toJSON());

Solution 2:

date.toJSON() prints the UTC-Date into a string formatted as json-date.

If you want your local-time to be printed, you have to use getTimezoneOffset(), which returns the offset in minutes. You have to convert this value into seconds and add this to the timestamp of your date:

var date = new Date(2012, 10, 30, 6, 51);
new Date(date.getTime() - (date.getTimezoneOffset() * 60000)).toJSON()

In a previous version of this answer, the offset was erroneously added instead of subtracted.


Post a Comment for "JavaScript Date.toJSON() Produces A Date Which Has Wrong Hours And Minutes"