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

Why does new.Date() differs 1 hour from new.Date().toISOString()?

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

我有以下代码:

<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()方法"take"距离new Date()1小时???

The toISOString() method returns a string in simplified extended ISO format (ISO 8601), which is always 24 characters long: YYYY-MM-DDTHH:mm:ss.sssZ. The timezone is always zero UTC offset, as denoted by the suffix "Z".

(强调我的)

MDN

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

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

旁注:

moment.js 是解决这些问题的好选择。