使用Javascript从时区名称获取时区偏移量

Har*_*gar 5 javascript jquery timezone timezone-offset

我发现许多解决方案都可以从偏移值中给出时区名称。但是我有时区名称,我想为此设置偏移值。我尝试了setTimezone('Asia / Kolkata'),但是我认为他们没有setTimezone这样的方法。

例:

Asia/Kolkata should give me -330 ( offset )
Run Code Online (Sandbox Code Playgroud)

Mr.*_*irl 31

这是使用现代 JavaScript 完成此任务的最简单方法。

注意:请记住,偏移量取决于夏令时 (DST) 是否处于活动状态。

/* @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
}
Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { top: 0; max-height: 100% !important; }
Run Code Online (Sandbox Code Playgroud)


小智 13

我遇到了同样的问题,这就是我提出的解决方案,如果您可以获得像您提到的那样的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]);
}

Run Code Online (Sandbox Code Playgroud)

这不是一个非常好的解决方案,但它无需导入任何内容即可完成工作。它依赖于 Intl.DateTimeFormat 的输出格式是否一致,这应该是一致的,但这是一个潜在的警告。


Mat*_*int 6

仅凭名字你无法得到它。您还需要知道具体时间。 Asia/Kolkata可能固定为单个偏移量,但许多时区在标准时间和夏令时之间交替,因此您不能只获取偏移量,而只能获取偏移量。

有关如何在 JavaScript 中执行此操作,请参阅此答案