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

Zid*_*rep 4 javascript methods datetime

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

我有以下代码:

<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>
Run Code Online (Sandbox Code Playgroud)

我得到以下结果:

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
Run Code Online (Sandbox Code Playgroud)

为什么该toISOString()方法“需要”1 小时new Date()

Rah*_*thi 6

尾随 Z(因此您面临差异)代表祖鲁时区。您的实际时间可能比 GMT 时间早 1 小时。如果您想消除因此而产生的差异,您可以尝试以下操作:

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

附注:

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