使时间独立于浏览器时区
Make time independent of browser time zone
我正在使用以下代码在 chrome 浏览器的控制台中打印时间戳,
moment("2021-01-12 00:00:00").utc().utcOffset(-new Date().getTimezoneOffset()).format('x')
此行打印给定时间和日期的时间戳。
如果我从“windows 日期和时间设置”更改时区,则上一行的输出也会更改。
无论当前浏览器的时区如何,如何使上一行的输出保持不变 window?
Date.protoype.getTime() 的文档指出:
The getTime() method returns the number of milliseconds* since the Unix Epoch.
* JavaScript uses milliseconds as the unit of measurement, whereas Unix Time is in seconds.
getTime() always uses UTC for time representation. For example, a client browser in one timezone, getTime() will be the same as a client browser in any other timezone.
因此,您从 Date 获得的时间戳始终是 UTC,并带有从主机环境 (OS) 获取的时区信息。
默认情况下 JavaScript(和时刻)将解析日期和时间,假设它们在用户的本地时区内,因此会受到 Windows 日期和时间设置更改的影响。
为了保持一致,您需要告诉 moment 将值解析为 UTC。
const timestamp = moment.utc("2021-01-12 00:00:00").format("x");
console.log(timestamp); // prints 1610409600000
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
无论您在哪个时区,您都应该将值 1610409600000
记录到控制台。
我正在使用以下代码在 chrome 浏览器的控制台中打印时间戳,
moment("2021-01-12 00:00:00").utc().utcOffset(-new Date().getTimezoneOffset()).format('x')
此行打印给定时间和日期的时间戳。
如果我从“windows 日期和时间设置”更改时区,则上一行的输出也会更改。
无论当前浏览器的时区如何,如何使上一行的输出保持不变 window?
Date.protoype.getTime() 的文档指出:
The getTime() method returns the number of milliseconds* since the Unix Epoch.
* JavaScript uses milliseconds as the unit of measurement, whereas Unix Time is in seconds.
getTime() always uses UTC for time representation. For example, a client browser in one timezone, getTime() will be the same as a client browser in any other timezone.
因此,您从 Date 获得的时间戳始终是 UTC,并带有从主机环境 (OS) 获取的时区信息。
默认情况下 JavaScript(和时刻)将解析日期和时间,假设它们在用户的本地时区内,因此会受到 Windows 日期和时间设置更改的影响。
为了保持一致,您需要告诉 moment 将值解析为 UTC。
const timestamp = moment.utc("2021-01-12 00:00:00").format("x");
console.log(timestamp); // prints 1610409600000
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
无论您在哪个时区,您都应该将值 1610409600000
记录到控制台。