gpt4 book ai didi

javascript - 为什么 new.Date() 与 new.Date().toISOString() 相差 1 小时?

转载 作者:行者123 更新时间:2023-11-29 19:28:45 26 4
gpt4 key购买 nike

请有人向我解释这种情况。

我有以下代码:

<p>Click the button to display the date and time as a string, using the ISO standard.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo1"></p>
<p id="demo"></p>

<script>
function myFunction() {
var d = new Date();
var n = d.toISOString();
document.getElementById("demo1").innerHTML = d;
document.getElementById("demo").innerHTML = n;
}
</script>

我得到以下结果:

Click the button to display the date and time as a string, using the ISO standard.

Try it

Mon Apr 06 2015 19:07:55 GMT+0100 (GMT Daylight Time)

2015-04-06T18:07:55.739Z

为什么 toISOString() 方法比 new Date()“占用”1 小时???

最佳答案

代表祖鲁时区的尾随 Z(因此您面临差异)。您的实际时间可能比 GMT 时间早 1 小时。如果你想摆脱差异,你可以试试这个:

var x = (new Date()).getTimezoneOffset() * 60000; 
var localISOTime = (new Date(Date.now() - x)).toISOString().slice(0,-1);

旁注:

moment.js 是选择摆脱这些问题的好选择。

关于javascript - 为什么 new.Date() 与 new.Date().toISOString() 相差 1 小时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29477072/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com