javascript .toISOString() 函数的问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16084313/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 03:13:05  来源:igfitidea点击:

Issue with .toISOString() function

javascript

提问by Amol M Kulkarni

Consider the following code HTML + JavaScript:

考虑以下代码 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>

Output:

输出

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

Could anyone help on understanding this difference in Date & Time

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

回答by Artyom Neustroev

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

I don't know, why would you need a ISO date a day earlier, but in case it is a typo:

我不知道,为什么你需要提前一天的 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

回答by John Kugelman

2013-18-04 00:00:00 GMT+0530
2013-17-04 18:30:00 GMT+0000

These are the two timestamps. The first one has a time zone, the second one is GMT (no time zone adjustment). If you take the second timestamp and add 05:30:00to 18:30:00you get midnight of the following day. That matches the first timestamp.

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

回答by Taras Shevchenko

Also you can remove timezone like this:

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

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