How to get timezone name (PDT, EST, etc.) in Javascript? [duplicate]

那年仲夏 提交于 2019-12-29 02:00:12

问题


Using Javascript, is there a way to get a user's timezone name (PDT, EST, etc.) based on the user's device?

Code I tried:

const timezone = jstz.determine()
const userTimezone = timezone.name()

But I would like to get back the user's timezone name in PDT, EST, etc. instead of America/New_York.


回答1:


Using moment.js with the moment-timezone add-on, you can do the following. The results will be consistent regardless of browser or operating system, because the abbreviations are in the data provided by the library.

The example results are from a computer set to the US Pacific time zone:

var zone = moment.tz.guess();            // "America/Los_Angeles"
var abbr = moment.tz(zone).format("z");  // either "PST" or "PDT", depending on when run

DISCLAIMER

Time zone abbreviations are not reliable or consistent. There are many different lists of them, and there are many ambiguities, such as "CST" being for Central Standard Time, Cuba Standard Time and China Standard Time. In general, you should avoid using them, and you should never parse them.

Also, the abbreviations in moment-timezone come from the IANA TZ Database. In recent editions of this data, many "invented" abbreviations have been replaced with numerical offsets instead. For example, if your user's time zone is Asia/Vladivostok, instead of getting "VLAT" like you may have in previous versions, you will instead get "+10". This is because the abbreviation "VLAT" was originally invented by the tz database to fill the data, and is not in actual use by persons in the area. Keep in mind that abbreviations are always in English also - even in areas where other language abbreviations might be in actual use.



来源:https://stackoverflow.com/questions/40494995/how-to-get-timezone-name-pdt-est-etc-in-javascript

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