本文介绍了为什么转换new.Date()。toISOString()会改变时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在以两种不同的格式在数据库中插入日期。

I'm inserting a date in a database in two different format.

这是插入日期时间

    var mydate;
    mydate = new Date();
    document.getElementById('clockinhour').value = mydate.toISOString().slice(0, 19).replace('T', ' ');

输出A

2017-06-21 20:14:31

这是插入为varchar:

document.getElementById('clocked_in_time').value = Date();

输出B

Wed Jun 21 2017 16:14:31 GMT-0400 (Eastern Standard Time)

输出B是正确的时间,但我需要显示输出A.什么原因导致转换为ISOString时的时间变化?我该如何解决这个问题?

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?

推荐答案

这是插入日期时间阻止你的 slice 正在剥离时区部分( Z 末尾的 toISOString 输出):

In your this is inserting as Datetime block your slice are stripping of the timezone part (the Z at the end of toISOString output):

document.getElementById('clockinhour').value = mydate.toISOString().slice(0, 19).replace('T', ' ');

正如@RobG在评论部分所指出的, toISOString 应始终以UTC格式返回日期( Z +00:00 )。

As pointed out by @RobG in the comments section, toISOString should always return the date in UTC (Z or +00:00).

时间更改,因为当您调用 toISOString 时,它会转换为UTC。

The time "changes" because it is converted to UTC when you calls toISOString.

如果你想在你的时区获得ISO日期,你应该看看这两个问题:和

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

这篇关于为什么转换new.Date()。toISOString()会改变时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-07 00:52