javascript 在Javascript中从时区获取UTC偏移量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20712419/
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 19:04:48  来源:igfitidea点击:

Get utc offset from timezone in Javascript

javascripttimezonedatejs

提问by user3124032

I need a Javascript function that given a timezone, returns the current utc offset.

我需要一个给定时区的 Javascript 函数,返回当前的 utc 偏移量。

For example, theFuncIneed('US/Eastern') -> 240

例如,theFuncIneed('US/Eastern') -> 240

Any idea?

任何的想法?

Thanks

谢谢

回答by Matt Johnson-Pint

In general, this is not possible.

一般来说,这是不可能的。

  • US/Easternis an identifier for a time zone. (It's actually an alias to America/New_York, which is the real identifier.)

  • 240is a time zone offset. It's more commonly written as -04:00(Invert the sign, divide by 60).

  • The US Eastern Time Zone is comprised of both Eastern Standard Time, which has the offset of -05:00and Eastern Daylight Time, which has the offset of -04:00.

  • US/Eastern时区的标识符。(它实际上是 的别名America/New_York,它是真正的标识符。)

  • 240是时区偏移量。更常见的写法是-04:00(反转符号,除以 60)。

  • 美国东部时区由偏移量为 的东部标准时间-05:00和偏移量为 的东部夏令时组成-04:00

So it is not at all accurate to say US/Eastern= 240. Please read the timezone tag wiki, especially the section titled "Time Zone != Offset".

所以说US/Eastern= 240一点也不准确。请阅读时区标签维基,尤其是标题为“时区!= 偏移”的部分。

Now you did ask for the currentoffset, which ispossible. If you supply a date+time reference, then you can resolve this.

现在您确实要求了当前偏移量,这可能的。如果您提供日期+时间参考,则可以解决此问题。

  • For the local time zone of the computer where the javascript code is executing, this is built in with .getTimeZoneOffset()from any instance of a Dateobject.

  • But if you want it for a specifictime zone, then you will need to use one of the libraries I listed here.

  • 对于执行 javascript 代码的计算机的本地时区,这是.getTimeZoneOffset()Date对象的任何实例内置的。

  • 但是,如果您希望在特定时区使用它,则需要使用我在此处列出的库之一

回答by Alexandru R

You can do this using moment.js

你可以使用moment.js来做到这一点

moment.tz('timezone name').utcOffset()

moment.tz('时区名称').utcOffset()

Although this involves using moment-timezone.js

虽然这涉及使用 moment-timezone.js