设置后瞬间时区更改为本地
Moment timezone changes to local after I set it
我有一段使用时区的 javascript 代码,我正在尝试计算相对于 America/Chicago 的日期,无论它在何处加载。然后稍后我将显示相对于用户本地时区 America/Chicago 发生的时间跨度。
var d = moment("18:00", "HH:mm").tz("America/Chicago");
第 31 行是我试图将日期设置为相对于 America/Chicago 的地方。日期是什么并不重要,重要的是时间 18:00。在代码的后面,第 36 行是我获取今天的日期以在第 38 行进行检查的地方
我试图让变量 datenum 显示今天相对于 America/Chicago 的日期编号,无论脚本加载到哪里。
当您使用 toDate()
从时刻转换为 Javascript 日期时,您将丢失时区信息并根据原始时刻的时间戳创建日期,因此您将获得对应于当地时区 18:00 的日期。在 this Github issue 中查看更详尽的解释:
The Date object has no time zone abilities other than working with the
local time zone. We can't do anything about that. When you use toDate,
any of moment or moment-timezone's ability to "represent" other time
zones is stripped away. You're left with the raw instant in time
represented by the timestamp [...]
You might as well have just done moment(1493092800000).toDate() or
moment.utc(1493092800000).toDate(). It's all the same as just new
Date(1493092800000).
您可以保留 moment 并使用 Moment 的 date()
方法:
var d = moment("18:00", "HH:mm").tz("America/Chicago");
var datenum = d.date();
这会告诉您当地的日期是什么,而芝加哥是18:00。
我有一段使用时区的 javascript 代码,我正在尝试计算相对于 America/Chicago 的日期,无论它在何处加载。然后稍后我将显示相对于用户本地时区 America/Chicago 发生的时间跨度。
var d = moment("18:00", "HH:mm").tz("America/Chicago");
第 31 行是我试图将日期设置为相对于 America/Chicago 的地方。日期是什么并不重要,重要的是时间 18:00。在代码的后面,第 36 行是我获取今天的日期以在第 38 行进行检查的地方
我试图让变量 datenum 显示今天相对于 America/Chicago 的日期编号,无论脚本加载到哪里。
当您使用 toDate()
从时刻转换为 Javascript 日期时,您将丢失时区信息并根据原始时刻的时间戳创建日期,因此您将获得对应于当地时区 18:00 的日期。在 this Github issue 中查看更详尽的解释:
The Date object has no time zone abilities other than working with the local time zone. We can't do anything about that. When you use toDate, any of moment or moment-timezone's ability to "represent" other time zones is stripped away. You're left with the raw instant in time represented by the timestamp [...]
You might as well have just done moment(1493092800000).toDate() or moment.utc(1493092800000).toDate(). It's all the same as just new Date(1493092800000).
您可以保留 moment 并使用 Moment 的 date()
方法:
var d = moment("18:00", "HH:mm").tz("America/Chicago");
var datenum = d.date();
这会告诉您当地的日期是什么,而芝加哥是18:00。