該賞金過期3天。這個問題的答案有資格獲得 50聲望獎勵。 Tri Nguyen想引起更多人對這個問題的關注。
有沒有辦法在 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()。這讓我認為這不是一個正確的解決方案。
有沒有人遇到過這個要求,并有一個很好的解決方案?
uj5u.com熱心網友回復:
你可以使用這樣的東西:
const actualDate = new Date()
actualDate.toLocaleString('en-US', { timeZone: 'America/New_York' })
uj5u.com熱心網友回復:
這能解決你的問題嗎?
function getDateInTZ(date, tz) {
return new Date(date).toLocaleString('en-US', { timeZone: tz })
}
console.log(getDateInTZ("2021-07-01 20:05", "Asia/Kolkata"))
console.log(getDateInTZ("2021-07-01 20:05", "America/Chicago"))
console.log(getDateInTZ("2021-12-06T02:05:00.000Z", "America/New_York"))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/341195.html
標籤:javascript 日期 火狐 时区
