简体   繁体   English

JavaScript的dateDate是1,时区偏移的问题?

[英]javascript dateDate is offset by 1, time zone issue?

I have the following code: 我有以下代码:

let date = new Date(event.eventDate); //2018-02-12T00:00:00.000Z
date = date.toISOString(); //try random thing here, but not helpful
date = new Date(date.split('T')[0]);
console.log(date, date.getDate()); //output is 11 on my local computer

so 2018-02-12 , getDate should be 12, but somehow on my local computer it returns 11. 所以2018-02-12getDate应该是12,但不知何故,我的本地计算机上返回11。

However, when i run the same code on remote server, it outputs getDate() correctly, which is "12". 然而,当我运行远程服务器上的同一个代码,它正确地输出GETDATE(),其是“12”。

how do i make sure the out put is always "12" no matter where i run the code? 我如何确保了放始终是“12”无论在哪里我运行代码?

Thanks! 谢谢!

getDate is interpretting the date in your local timezone, which is a few hours behind the UTC version of the date, which your server is using. getDate被训释在本地时区,这是后面的日期UTC版本,你的服务器使用的是几个小时的日期。 Since the time of the date is midnight, the offset of your local timezone sets it to the prior day. 由于日期的时间是午夜,你的本地时区的偏移将其设置为前一天。 You can replace getDate with getUTCDate to use the UTC value 您可以将getDate替换为getUTCDate以使用UTC值

let date = new Date(event.eventDate); //2018-02-12T00:00:00.000Z
console.log(date.getUTCDate()) // 12

According to MDN: 根据MDN:

The getDate() method returns the day of the month for the specified date according to local time. getDate()方法根据当地时间返回指定日期的月份。

If you're looking for a fixed (UTC) date that will be the same for each person, you can use getUTCDate() : 如果您要寻找一个每个人都相同的固定(UTC)日期,则可以使用getUTCDate()

 let date = new Date('2018-02-12T00:00:00.000Z'); date = date.toISOString(); date = new Date(date.split('T')[0]); console.log(date, date.getDate()); console.log(date, date.getUTCDate()); 

Hope this helps! 希望这可以帮助!

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

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