JavaScript Date.toJSON()产生的日期带有错误的小时和分钟 [英] JavaScript Date.toJSON() produces a date which has wrong hours and minutes
本文介绍了JavaScript Date.toJSON()产生的日期带有错误的小时和分钟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将日期打印为 ISO-8601
标准: YYYY-MM-DDTHH:mm:ss.sssZ
,所以我使用了以下几行代码,但是我得到了意外的输出
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());
对应的输出是
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
toJSON()方法可正确打印小时和分钟,而toString()可正确打印,我想知道这是什么原因.我是否必须向Date对象添加时间偏移,如果是,那么如何?
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?
推荐答案
var date = new Date();
console.log(date.toJSON(), new Date(date.getTime() - (date.getTimezoneOffset() * 60000)).toJSON());
这篇关于JavaScript Date.toJSON()产生的日期带有错误的小时和分钟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文