【问题标题】:Get Offset of the other Location in Javascript在 Javascript 中获取其他位置的偏移量
【发布时间】:2020-06-01 11:18:27
【问题描述】:
我在亚洲,我想计算澳大利亚的偏移量。我知道如何计算偏移量的值,代码写在下面:
var timezone_offset = new Date().getTimezoneOffset();
但是如何计算其他位置的呢?谁能指导我??
【问题讨论】:
标签:
javascript
date
datetime
【解决方案1】:
虽然这个可以在一个简短的函数中完成,但最好使用库,因为有许多怪癖需要克服。可以使用toLocaleString 或Intl.DateTimeFormat 的时区选项来确定偏移量。
但是,如果用于格式化的语言与位置的语言相匹配,它会返回时区缩写而不是偏移量。为了解决这个问题,以下函数首先使用英语,如果返回缩写而不是偏移量,则使用法语。英语偏移量以 GMT 开头,法语偏移量以 UTC 开头。当偏移量为 +0 时,它们只返回“GMT”或“UTC”。
它已经在wikipedia 列出的所有 IANA 位置上进行了测试,并且似乎适用于所有位置,但它应该进行更广泛的测试。此外,在尝试运行它之前应该进行功能测试(即支持 Int.DateTimeFormat 构造函数、formatToParts 方法和 timeZoneName 选项)。
// Return offset on date for loc in ±H[:mm] format. Minutes only included if not zero
function getTimezoneOffset(date, loc) {
// Try English to get offset. If get abbreviation, use French
let offset;
['en','fr'].some(lang => {
// Get parts - can't get just timeZoneName, must get one other part at least
let parts = new Intl.DateTimeFormat(lang, {
minute: 'numeric',
timeZone: loc,
timeZoneName:'short'
}).formatToParts(date);
// Get offset from parts
let tzName = parts.filter(part => part.type == 'timeZoneName' && part.value);
// timeZoneName starting with GMT or UTC is offset - keep and stop looping
// Otherwise it's an abbreviation, keep looping
if (/^(GMT|UTC)/.test(tzName[0].value)) {
offset = tzName[0].value.replace(/GMT|UTC/,'') || '+0';
return true;
}
});
// Format offset as ±HH:mm
// Normalise minus sign as ASCII minus (charCode 45)
let sign = offset[0] == '\x2b'? '\x2b' : '\x2d';
let [h, m] = offset.substring(1).split(':');
return sign + h.padStart(2, '0') + ':' + (m || '00');
}
let d = new Date();
console.log('Current offset for following locations:');
['Australia/Yancowinna',
'Australia/Lord_Howe',
'Australia/Canberra',
'Pacific/Honolulu',
'Europe/London',
'Canada/Eastern'
].forEach( loc =>
console.log(loc + ': ' + getTimezoneOffset(d, loc))
);
我不建议你使用这个函数,它真的是为了展示获取特定位置的偏移量是多么的麻烦。
请注意,澳大利亚有许多偏移量,有些地方遵守夏令时,而其他地方则没有。