Javascript 为什么转换 new.Date() .toISOString() 会改变时间?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44689770/
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
Why converting new.Date() .toISOString() changes the time?
提问by Sebastian Farham
I'm inserting a date in a database in two different format.
我正在以两种不同的格式在数据库中插入日期。
this is inserting as Datetime
这是作为日期时间插入
var mydate;
mydate = new Date();
document.getElementById('clockinhour').value = mydate.toISOString().slice(0, 19).replace('T', ' ');
Output A
输出 A
2017-06-21 20:14:31
this is inserting as varchar :
这是作为 varchar 插入:
document.getElementById('clocked_in_time').value = Date();
Output B
输出 B
Wed Jun 21 2017 16:14:31 GMT-0400 (Eastern Standard Time)
Output B is the correct time but I need to display output A. What causes the time to change when converted toISOString? How can I fix this?
输出 B 是正确的时间,但我需要显示输出 A。是什么导致转换为 ISOString 时时间发生变化?我怎样才能解决这个问题?
回答by Dinei
In your this is inserting as Datetimeblock your sliceare stripping of the timezone part (the Zat the end of toISOStringoutput):
在您这是作为 Datetime块插入时,您slice正在剥离时区部分(Z在toISOString输出末尾):
document.getElementById('clockinhour').value = mydate.toISOString().slice(0, 19).replace('T', ' ');
As pointed out by @RobG in the comments section, toISOStringshould always return the date in UTC (Zor +00:00).
正如@RobG 在评论部分指出的那样,toISOString应始终以 UTC(Z或+00:00)返回日期。
RTFM: "The time zone [offset] is always UTC, denoted by the suffix Z",
RTFM:“时区[偏移量]始终为UTC,由后缀Z表示”,
The time "changes" because it is converted to UTC when you calls toISOString.
时间“改变”是因为当您调用toISOString.
If you want to get ISO date in your timezone, you should take a look in these two questions: How to ISO 8601 format a Date with Timezone Offset in JavaScript?and How to format a JavaScript date
如果您想在您的时区中获取 ISO 日期,您应该查看以下两个问题:How to ISO 8601 format a Date with Timezone Offset in JavaScript?以及如何格式化 JavaScript 日期
回答by ControlAltDel
ISO time is time zone free. You'll notice with b you have time zone GMT-04:00 if you add those four hours to the 16 hours in the Date, you get 20
ISO 时间不受时区限制。你会注意到 b 你有时区 GMT-04:00 如果你把这四个小时加到日期中的 16 小时,你得到 20
回答by Nafis
Just if someone else face the same issue and visit this question.
只是如果其他人面临同样的问题并访问此问题。
There is a solution here: https://stackoverflow.com/a/28149561
这里有一个解决方案:https: //stackoverflow.com/a/28149561

