Issue with converting Date to JSON in javascript

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.


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?

链接地址: http://www.djcxy.com/p/77508.html

上一篇: Javascript日期以指定的格式

下一篇: 在JavaScript中将日期转换为JSON的问题