如何在 JavaScript 中获取时区名称?

2022-01-16 00:00:00 timezone javascript

我知道如何获取时区偏移量,但我需要的是能够检测美国/纽约"之类的内容.这甚至可以通过 JavaScript 实现,还是我必须根据偏移量来猜测?

I know how to get the timezone offset, but what I need is the ability to detect something like "America/New York." Is that even possible from JavaScript or is that something I am going to have to guestimate based on the offset?

推荐答案

国际化 API 支持获取用户时区,支持在所有当前的浏览器中.

The Internationalization API supports getting the user timezone, and is supported in all current browsers.

console.log(Intl.DateTimeFormat().resolvedOptions().timeZone)

请记住,在一些支持国际化 API 的旧浏览器版本上,timeZone 属性设置为 undefined 而不是用户的时区字符串.据我所知,在撰写本文时(2017 年 7 月)除 IE11 之外的所有当前浏览器 都会将用户时区作为字符串返回.

Keep in mind that on some older browser versions that support the Internationalization API, the timeZone property is set to undefined rather than the user’s timezone string. As best as I can tell, at the time of writing (July 2017) all current browsers except for IE11 will return the user timezone as a string.

相关文章