Get UTC offset from timezone abbreviations

眉间皱痕 提交于 2020-11-25 03:57:03

问题


Is there anyway to get utc offset from a timezone abbreviations? Such as:

"PST"

for

Pacific Standard Time (North America)

which will result in UTC−08. I found a way on moment-timezone but it did not help much. It provides a list of timezone identifier but most of them are deprecated. Thank you.


回答1:


This is a quite tricky topic and similar questions have already been discussed.

See Detect timezone abbreviation using JavaScript or Get timezone abbreviation using offset value

I would propose two options:

1. Hash table. Create a key-value pair of what you require based on standard information (e.g. list of timezone abbreviations and their offset). Something like

    let offsetByAbbrev = {"PST" : "UTC-08", "EST" : "UTC+01", ... }

But this needs serious maintenance as it will get deprecated quickly.

2. Date manipulation. You can create a date in a specific timezone with momentjs, however, not with abbreviations. And there is a good reason for it: these abbreviations can change and can also cause ambiguity. You can check out the JSON used by momentjs-timezone: https://github.com/moment/moment-timezone/blob/develop/data/packed/latest.json which will give you a general sense of how chaotic it can be. For example do a simple ctrl+f search for PST and see the results.

So I would suggest using the timezone names - which you can actually create and use with momentjs-timezone. See How to create time in a specific time zone with moment.js where you can create a moment object based on the timezone name and that object will contain (as per the spec of moment timezone: https://momentjs.com/timezone/docs/#/zone-object/) the offset itself.

I know this does not exactly resolve your problem, though what you are trying to do is not necessarily the best approach to reach your an ideal solution.



来源:https://stackoverflow.com/questions/60147015/get-utc-offset-from-timezone-abbreviations

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