Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Date.toJSON() produces a date which has wrong hours and minutes

Tags:

javascript

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?

like image 549
Arif Nadeem Avatar asked Nov 30 '12 13:11

Arif Nadeem


People also ask

How to get time from Date in JavaScript?

JavaScript Date getTime() getTime() returns the number of milliseconds since January 1, 1970 00:00:00.

What is toJSON in JavaScript?

The toJSON() method returns a date object as a string, formatted as a JSON date.

How to get time from timestamp in JavaScript?

If you instead want to get the current time stamp, you can create a new Date object and use the getTime() method. const currentDate = new Date(); const timestamp = currentDate. getTime(); In JavaScript, a time stamp is the number of milliseconds that have passed since January 1, 1970.


1 Answers

var date = new Date();
console.log(date.toJSON(), new Date(date.getTime() - (date.getTimezoneOffset() * 60000)).toJSON());
like image 195
Sushil Dravekar Avatar answered Sep 29 '22 23:09

Sushil Dravekar