.toISOString() 函数的问题

Posted

技术标签:

【中文标题】.toISOString() 函数的问题【英文标题】:Issue with .toISOString() function 【发布时间】:2013-04-11 15:33:24 【问题描述】:

考虑以下代码 html + javascript

<!DOCTYPE html>
<html>
<body>

<p id="demo">Click the button to display a date after changing the hours, minutes, and seconds.</p>

<button onclick="myFunction()">Try it</button>
 <script>
 function myFunction()
  
  var d = new Date();
  d.setHours(0,0,0,0);
  document.write(d + '<br/>');
  document.write('ISO Date '+ d.toISOString() + '<br/>');
  //I want it to be 2013-04-17T00:00:00.000Z
  
 </script>
</body>
</html>

输出

Thu Apr 18 2013 00:00:00 GMT+0530 (India Standard Time)
ISO Date 2013-04-17T18:30:00.000Z

任何人都可以帮助理解日期和时间的这种差异

【问题讨论】:

【参考方案1】:

您也可以像这样删除时区:

let birthday = new Date(this.profile.birthday + ' UTC').toISOString();

【讨论】:

【参考方案2】:
var d = new Date();
d.setHours(-12, d.getTimezoneOffset(), 0, 0); //removing the timezone offset and 12 hours
console.log(d.toISOString()); //2013-04-17T00:00:00.000Z

我不知道,为什么您需要提前一天提供 ISO 日期,但万一是错字:

var d = new Date();
d.setHours(0, -d.getTimezoneOffset(), 0, 0); //removing the timezone offset.
console.log(d.toISOString()); //2013-04-18T00:00:00.000Z

【讨论】:

第二个例子,我认为应该是d.getTimezoneOffset()。偏移量可以是负数或正数。如果值为负,则否定将创建一个加法。 @dbasch 这就是重点。如果该值为负数,那么您在 落后 UTC0,因此您需要将小时数添加到您的本地时间。【参考方案3】:
2013-18-04 00:00:00 GMT+0530
2013-17-04 18:30:00 GMT+0000

这是两个时间戳。第一个有时区,第二个是 GMT(无时区调整)。如果您采用第二个时间戳并将05:30:00 添加到18:30:00,您将获得第二天的午夜。这与第一个时间戳匹配。

【讨论】:

值得注意的是 OP 代码中的注释://I want it to be 2013-04-17T00:00:00.000Z。我认为他正在寻找一种方法来防止 .toISOString() 从 GMT+0530 转换为 GMT+0000。 @JamesDonnelly:你是对的......我从 Artyom Neustroev 那里得到了答案,即删除时区偏移量。无论如何感谢大家的时间 那些“GMT”后缀不是时区,而是偏移量。他们对夏令时的调整一无所知。

以上是关于.toISOString() 函数的问题的主要内容,如果未能解决你的问题,请参考以下文章

javascript toISOString() 忽略时区偏移

date-fns 中的啥方法相当于 moment().toISOString()

Safari 为 Date toISOString() 返回了不正确的值

toISOString 在 iPhone 中无法与 Cordova Ionic 一起使用

js 日期格式化小问题

javascript toISOString()忽略时区偏移量