【发布时间】:2021-12-06 23:08:30
【问题描述】:
有没有办法在 JavaScript 中获取指定时区的本地时间?基本上,我在想办法说,纽约下午 2 点的 ISO 时间字符串是多少?
我有一个技巧,其中date 是可解析的日期字符串,tz 是时区标识符,例如America/New_York。
function getDateInTZ(date, tz) {
const formatter = new Intl.DateTimeFormat([], {
year: "numeric",
month: "numeric",
day: "numeric",
hour: "numeric",
minute: "numeric",
second: "numeric",
fractionalSecondDigits: 3,
timeZone: tz,
});
const localDate = new Date(date);
const localDateAtTZ = new Date(formatter.format(localDate));
const tzOffset = localDate.getTime() - localDateAtTZ.getTime();
return new Date(localDate.getTime() + tzOffset);
}
它具有以下行为
getDateInTz("2021-07-01 20:05", "America/Chicago").toISOString(); // 2021-07-02T01:05:00.000Z
getDateInTz(new Date("2021-12-05 20:05"), "America/Chicago").toISOString(); // 2021-12-06T02:05:00.000Z
getDateInTz("2021-12-06T02:05:00.000Z", "America/New_York").toISOString(); // 2021-12-06T02:05:00.000Z if local time is NY
getDateInTz("2021-12-06T02:05:00.000Z", "America/New_York").toISOString(); // 2021-12-06T07:05:00.000Z if local time is UTC
虽然上述解决方案适用于 Chrome,但它不适用于 Firefox,因为 FF 无法对 formatter.format() 的输出执行 Date.parse。这让我认为这不是一个正确的解决方案。
之前有没有人遇到过这个需求,并且有好的解决方案?
【问题讨论】:
-
也许你真的想要一个普通的 JS 解决方案?不过,我强烈推荐npmjs.com/package/moment-timezone
-
@FishSaidNo 你有没有我提到的使用时刻时区的代码?
标签: javascript date firefox timezone