JavaScript Date.toJSON() 产生的日期有错误的小时和分钟

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13646446/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 19:21:53  来源:igfitidea点击:

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

javascript

提问by Arif Nadeem

I want to print a Date to ISO-8601standard: YYYY-MM-DDTHH:mm:ss.sssZso I used the following lines of code, but I am getting unexpected output

我想打印一个日期到ISO-8601标准:YYYY-MM-DDTHH:mm:ss.sssZ所以我使用了以下代码行,但我得到了意外的输出

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?

toJSON() 方法错误地打印小时和分钟,但 toString() 正确打印,我想知道这是什么原因。我是否必须向 Date 对象添加时间偏移量,如果是,那么如何?

回答by Sushil Dravekar

var date = new Date();
console.log(date.toJSON(), new Date(date.getTime() - (date.getTimezoneOffset() * 60000)).toJSON());

回答by hereandnow78

date.toJSON()prints the UTC-Date into a string formatted as json-date.

date.toJSON()将 UTC-Date 打印为格式为 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:

如果您希望打印本地时间,则必须使用getTimezoneOffset(),它以分钟为单位返回偏移量。您必须将此值转换为秒并将其添加到日期的时间戳中:

var date = new Date(2012, 10, 30, 6, 51);
new Date(date.getTime() + (date.getTimezoneOffset() * 60000)).toJSON()