gpt4 book ai didi

javascript - 如何在 JavaScript 中从 IANA 时区代码获取时区偏移量?

转载 作者:太空宇宙 更新时间:2023-11-04 15:46:18 25 4
gpt4 key购买 nike

我有IANA时区代码,如“亚洲/加尔各答”,我需要在 JavaScript 中获取时区偏移量,如 -330。我无法获得时区偏移,我们将不胜感激。

最佳答案

使用 native Date.toLocaleString API:

function timeZoneOffsetInMinutes(ianaTimeZone) {
const now = new Date();
now.setSeconds(0, 0);

// Format current time in `ianaTimeZone` as `M/DD/YYYY, HH:MM:SS`:
const tzDateString = now.toLocaleString('en-US', {
timeZone: ianaTimeZone,
hourCycle: 'h23',
});

// Parse formatted date string:
const match = /(\d+)\/(\d+)\/(\d+), (\d+):(\d+)/.exec(tzDateString);
const [_, month, day, year, hour, min] = match.map(Number);

// Change date string's time zone to UTC and get timestamp:
const tzTime = Date.UTC(year, month - 1, day, hour, min);

// Return the offset between UTC and target time zone:
return Math.floor((tzTime - now.getTime()) / (1000 * 60));
}

关于javascript - 如何在 JavaScript 中从 IANA 时区代码获取时区偏移量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43538958/

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