简体   繁体   English

为什么Javascript会显示错误的日期?

[英]Why does Javascript show me the wrong date?

Consider the following date object which is created in JavaScript. 考虑以下在JavaScript中创建的date对象。

var date = new Date("2017-09-07T16:46:06.000Z");

This date object should be equivalent to Sep 7 2017 4:46:06 PM 此日期对象应等效于2017年9月7日下午4:46:06

However, in the browser console, when I type the following: 但是,在浏览器控制台中,当我键入以下内容时:

console.log(date);

The following is returned: 返回以下内容:

Fri Sep 08 2017 02:46:06 GMT+1000 (E. Australia Standard Time) 2017年9月8日星期五02:46:06 GMT + 1000(澳大利亚标准时间)

The time is wrong. 时间错了。 (It actually is today's date, but the time is completely wrong). (实际上是今天的日期,但是时间是完全错误的)。

Key points of confusion: 混淆的要点:

  • My computer timezone is set to GMT+1000 (Australia/Brisbane) 我的计算机时区设置为GMT + 1000(澳大利亚/布里斯班)
  • When I created the date object, I did not specify the timezone, therefore it should conform to my systems timezone 创建日期对象时,我没有指定时区,因此它应符合我的系统时区
  • When I log the date object to the console, it is still using GMT+1000 (Australia/Brisbane) but the date is different 当我将日期对象记录到控制台时,它仍在使用GMT + 1000(澳大利亚/布里斯班),但日期不同

When you created the date, you did specify a timezone. 创建日期时, 确实指定了时区。 That Z at the end means Zulu or Greenwich Mean Time. 末尾的Z表示祖鲁或格林威治标准时间。 Your computer is 10 hours off from GMT, so it adjusts to your local timezone for display. 您的计算机距离格林威治标准时间10个小时,因此它会调整为适合您当地的时区显示。

If you want the date to be in your local time zone, remove the Z 如果您希望日期在当地时区,请删除Z

var date = new Date("2017-09-07T16:46:06.000Z");

So it looks like the Z at the end of your date string is meant to represent UTC or Zulu time 因此,看起来日期字符串末尾的Z代表UTC或Zulu时间

var date = new Date("2017-09-07T16:46:06.000");

should be the correct solution 应该是正确的解决方案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM