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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21327371/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 20:39:37  来源:igfitidea点击:

Get timezone offset from timezone name using Javascript

javascriptjquerytimezonetimezone-offset

提问by Hardik Sondagar

I found many solution that gives Timezone name from offset value. But I have Timezone name and I want offset value for that. I tried setTimezone('Asia/Kolkata'), but I think their is no method like setTimezone.

我找到了许多从偏移值给出时区名称的解决方案。但我有时区名称,我想要偏移值。我试过 setTimezone('Asia/Kolkata'),但我认为它们不像 setTimezone 那样的方法。

example:

例子:

Asia/Kolkata should give me -330 ( offset )

回答by Matt Johnson-Pint

You can't get it by name alone. You would also need to know the specific time. Asia/Kolkatamay be fixed to a single offset, but many time zones alternate between standard time and daylight saving time, so you can't just get theoffset, you can only get anoffset.

仅凭名字是无法得到它的。您还需要知道具体时间。 Asia/Kolkata可以固定到一个单一的偏移,但很多时区的标准时间和夏令时之间交替,所以你不能只是得到弥补,你只能得到一个偏移量。

For how to do it in JavaScript, see this answer.

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

回答by Nathan Dullea

Using countries and timezonesnpm package:

使用国家和时区npm 包:

import {getTimezone} from 'countries-and-timezones';
const australianTimezone = 'Australia/Melbourne';
console.log(getTimezone(australianTimezone));

Prints to the console:

打印到控制台:

{
  name: 'Australia/Melbourne',
  country: 'AU',
  utcOffset: 600,
  utcOffsetStr: '+10:00',
  dstOffset: 660,
  dstOffsetStr: '+11:00',
  aliasOf: null
}

From there, you can use the utcOffset or dstOffset depending on if it is daylight savings time.

从那里,您可以根据是否为夏令时使用 utcOffset 或 dstOffset。