Get utc offset from timezone in Javascript

纵然是瞬间 提交于 2019-12-04 00:43:57

问题


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

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

Any idea?

Thanks


回答1:


In general, this is not possible.

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

  • 240 is 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:00 and Eastern Daylight Time, which has the offset of -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".

Now you did ask for the current offset, which is possible. 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 Date object.

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




回答2:


You can do this using moment.js

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

Although this involves using moment-timezone.js



来源:https://stackoverflow.com/questions/20712419/get-utc-offset-from-timezone-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!