Question

Once the Date object is created as,

var oDate = new Date(2014,01,21,23,00,00);

It returns Fri Feb 21 2014 23:00:00 GMT+0530 (India Standard Time). But when i try to convert it to JSON.

oDate.toJSON() // "2014-02-21T17:30:00.000Z"

Why is the Hours and minutes getting changed ? The Hours should be 23 and minutes should be 00.

Was it helpful?

Solution

When you call toJSON() on a Date object it returns a string representing the Date using toISOString() which conforms to the ISO8601 standard e.g. YYYY-MM-DDTHH:mm:ss.sssZ. The timezone is always UTC, hence the difference in your example.

Se here for more information of the Date object in Javascript.

There are a few things to mention with regards to your example:

  1. A date and time are locale specific, your browser establishes this based on your system clock (you can change this).
  2. When you serialise a date and time this locale information will be converted to a timestamp.
  3. If you were to persist this timestamp in a database and then reload this information into the browser using Date.parse() and then your browser would display this in the date and time correct for your current timezone e.g. India Standard Time.

I have created a simple jsFiddle to serve as an example. In my current timezone GMT, this serves an important example when looking at winterDate and summerDate, as in Summer in this timezone we enter daylight savings and advance time by one hour. What is important is that Javascript understands this and captures the timezone so the universal value of the time something occurred is preserved. If you change your system's timezone and then reload your browser you will be able to see this behaviour for yourself.

I hope this helps give you a bit more understanding of this behaviour, and why it is important.

OTHER TIPS

Why is the Hours and minutes getting changed?

Because it's no more expressed with India Standard Time as displayed in your console, but UTC (Z ulu Time as denoted in the ISO 8601 string).

The Hours should be 23 and minutes should be 00.

No. If you want to create a 23:00 time in UTC, then you should use

var oDate = new Date(Date.UTC(2014,01,21,23,00,00));

This is actually working as intended and serialized to UTC, as when you load the JSON object you get the correct Date again. The time was stored in UTC when using toJSON().

Specified by:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toJSON

Test code:

var oDate = (new Date()).toJSON();
var pDate = new Date(oDate);

console.log("Serialized date object: " + oDate);
console.log("Actual date object: " + pDate);

Just for the record, remember that the last "Z" in "2014-02-21T17:30:00.000Z" means that the time is indeed in UTC

For more information :-

http://en.wikipedia.org/wiki/ISO_8601

For reference :-

How do I format a Microsoft JSON date?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top