基于位置的 MomentJS 时区
MomentJS Timezone based on location
如果我在 VPS 服务器中使用 momentJS,它会根据服务器所在的位置创建日期和时间吗?
例如:
如果我的服务器在A国某处,客户端访问B国的站点,momentJS创建时间是基于A国还是B国?
希望这个问题有道理..
Moment.js 通常会在运行代码的机器上使用配置的时间和时区。
但是您也可以创建一个时刻实例设置为 UTC
时间,您还可以使用 Moment Timezone 获取任何时区的时间,例如America/Los_Angeles等
我建议在服务器上下文中使用 UTC 时间以使事件保持一致。这样,如果您更改服务器位置,就不会遇到问题。所有事件均以 UTC 记录,客户可以根据需要转换为当地时间。
// Local time (of machine running code e.g. server)
console.log('Local time:', moment().format());
// UTC time
console.log('UTC time :', moment.utc().format());
const timezones = ['America/Los_Angeles', 'Europe/Paris'];
console.log('Time in timezones:');
for(let tz of timezones) {
console.log(`Time in timezone ${tz}:`, moment.tz(tz).format());
}
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone-with-data-1970-2030.js"></script>
如果我在 VPS 服务器中使用 momentJS,它会根据服务器所在的位置创建日期和时间吗?
例如:
如果我的服务器在A国某处,客户端访问B国的站点,momentJS创建时间是基于A国还是B国?
希望这个问题有道理..
Moment.js 通常会在运行代码的机器上使用配置的时间和时区。
但是您也可以创建一个时刻实例设置为 UTC
时间,您还可以使用 Moment Timezone 获取任何时区的时间,例如America/Los_Angeles等
我建议在服务器上下文中使用 UTC 时间以使事件保持一致。这样,如果您更改服务器位置,就不会遇到问题。所有事件均以 UTC 记录,客户可以根据需要转换为当地时间。
// Local time (of machine running code e.g. server)
console.log('Local time:', moment().format());
// UTC time
console.log('UTC time :', moment.utc().format());
const timezones = ['America/Los_Angeles', 'Europe/Paris'];
console.log('Time in timezones:');
for(let tz of timezones) {
console.log(`Time in timezone ${tz}:`, moment.tz(tz).format());
}
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone-with-data-1970-2030.js"></script>