gpt4 book ai didi

JavaScript:如何获取指定时区的日期时间

转载 作者:行者123 更新时间:2023-12-04 13:24:11 26 4
gpt4 key购买 nike

有没有办法在 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 无法执行 Date.parse关于 formatter.format() 的输出.这让我认为这不是一个正确的解决方案。
有没有人遇到过这个要求,并有一个很好的解决方案?

最佳答案

据我所知,如果没有像 luxon 这样的图书馆的帮助,这是不可能的。或 day.js
在 luxon 这将是要走的路

let local = luxon.DateTime.local();  // 2021-10-31T20:26:15.093+01:00
let localInCT = local.setZone("America/Chicago"); //2021-10-31T14:26:15.093-05:00
看看 this project使用这些方法

关于JavaScript:如何获取指定时区的日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69640726/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com