我发现了很多解决方案可以从偏移值获取时区名称。但是我有时区名称,我想要该时区的偏移值。我尝试了setTimezone('Asia/Kolkata'),但我认为没有像setTimezone这样的方法。
例子:
Asia/Kolkata should give me -330 ( offset )
我发现了很多解决方案可以从偏移值获取时区名称。但是我有时区名称,我想要该时区的偏移值。我尝试了setTimezone('Asia/Kolkata'),但我认为没有像setTimezone这样的方法。
例子:
Asia/Kolkata should give me -330 ( offset )
/* @return A timezone offset in minutes */
const getOffset = (timeZone = 'UTC', date = new Date()) => {
const utcDate = new Date(date.toLocaleString('en-US', { timeZone: 'UTC' }));
const tzDate = new Date(date.toLocaleString('en-US', { timeZone }));
return (tzDate.getTime() - utcDate.getTime()) / 6e4;
}
console.log(`No arguments: ${getOffset()}`); // 0
{
console.log('! Test Case #1 >> Now');
console.log(`Asia/Colombo : ${getOffset('Asia/Colombo')}`); // 330
console.log(`America/New_York : ${getOffset('America/New_York')}`); // -240
}
{
console.log('! Test Case #2 >> DST : off');
const date = new Date(2021, 0, 1);
console.log(`Asia/Colombo : ${getOffset('Asia/Colombo', date)}`); // 330
console.log(`America/New_York : ${getOffset('America/New_York', date)}`); // -300
}
{
console.log('! Test Case #3 >> DST : on');
const date = new Date(2021, 5, 1);
console.log(`Asia/Colombo : ${getOffset('Asia/Colombo', date)}`); // 330
console.log(`America/New_York : ${getOffset('America/New_York', date)}`); // -240
}
.as-console-wrapper { top: 0; max-height: 100% !important; }
Date.parse()
代替new Date()
。2. 将字符串' Z'
添加到toLocaleString()
的输出中,并且该函数根据夏令时是否激活而给出不同的偏移量:Date.parse(date.toLocaleString(systemTimeZone, { timeZone }) + ' Z')
- some我遇到了同样的问题,这是我想出的解决方案,如果你能获取一个像你提到的IANA tz 数据库名称:
const myTimezoneName = "Asia/Colombo";
// Generating the formatted text
// Setting the timeZoneName to longOffset will convert PDT to GMT-07:00
const options = {timeZone: myTimezoneName, timeZoneName: "longOffset"};
const dateText = Intl.DateTimeFormat([], options).format(new Date);
// Scraping the numbers we want from the text
// The default value '+0' is needed when the timezone is missing the number part. Ex. Africa/Bamako --> GMT
let timezoneString = dateText.split(" ")[1].slice(3) || '+0';
// Getting the offset
let timezoneOffset = parseInt(timezoneString.split(':')[0])*60;
// Checking for a minutes offset and adding if appropriate
if (timezoneString.includes(":")) {
timezoneOffset = timezoneOffset + parseInt(timezoneString.split(':')[1]);
}
这不是一个非常好的解决方案,但它可以在不导入任何内容的情况下完成工作。它依赖于 Intl.DateTimeFormat 的输出格式始终保持一致,这应该是如此,但这是一个潜在的警告。
Asia/Kolkata
可能固定为单个偏移量,但许多时区在标准时间和夏令时之间交替,因此你只能获取一个偏移量,而不能获取唯一的偏移量。import {getTimezone} from 'countries-and-timezones';
const australianTimezone = 'Australia/Melbourne';
console.log(getTimezone(australianTimezone));
打印到控制台:
{
name: 'Australia/Melbourne',
country: 'AU',
utcOffset: 600,
utcOffsetStr: '+10:00',
dstOffset: 660,
dstOffsetStr: '+11:00',
aliasOf: null
}
从那里开始,您可以根据是否为夏令时使用utcOffset或dstOffset。