9

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, 51);
print('UTC Format: '+date.toGMTString());
print('toString() method: '+date.toString());
print('toJSON() method: '+date.toJSON());//print hours and minutes incorrectly
print('to UTCString() method: ' + date.toUTCString());

The corresponding output is

UTC Format: Fri, 30 Nov 2012 01:21:00 GMT
toString() method: Fri Nov 30 2012 06:51:00 GMT+0530 (India Standard Time)
toJSON() method: 2012-11-30T01:21:00.000Z
to UTCString() method: Fri, 30 Nov 2012 01:21:00 GMT

The toJSON() method prints hours and minutes incorrectly but toString() prints it correctly, I wanted to know what is the reason for that. Do I have to add time offset to the Date object, if yes then how?

4
  • the toJSON part subtracts my hours and minutes by 5:30 hours which is India's GMT time Nov 30, 2012 at 13:50
  • GMT = Greenwich Mean Time which is not India's.
    – xiaoyi
    Nov 30, 2012 at 13:51
  • I meant its gmt + 5.30 for India Nov 30, 2012 at 13:57
  • We noticed such effect when saving the date in database. We use pikaday for selecting the date and use toJSON method to serialize date before sending to the server, but when we get this date back and put it in pikaday, control(Date objects) corrects the date according to your offset. So be careful when you use this method, maybe you have to use somethig else in your case.
    – setty
    Nov 10, 2016 at 13:45

2 Answers 2

36
var date = new Date();
console.log(date.toJSON(), new Date(date.getTime() - (date.getTimezoneOffset() * 60000)).toJSON());
1
  • @abimelex you and others were right, i corrected my answer Feb 15, 2018 at 20:28
8

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.

2
  • How do I do that in case of my question, say I defined var date = new Date(2012, 10, 30, 6, 51); how do I use defaultTimezoneOffset method to add the remaining 5.30 hours? Nov 30, 2012 at 13:58
  • This gives me the wrong result. The answer of Sushil Dravekar gives the right result.
    – mvermand
    Jan 19, 2018 at 9:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.