在JavaScript中是否有一种方法可以获得与指定时区本地相关的时间?基本上,我想知道,在纽约时间下午2点的ISO时间字符串是什么。
我有一个hack来做到这一点,其中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中无法对formatter.format()
的输出执行Date.parse
,这导致我认为它不是一个正确的解决方案。
是否有人之前遇到过这种情况,并且有一个好的解决方案呢?