如何在 Javascript 中获取浏览器的时区字符串

How to get the timezone string of the browser in Javascript?

本文关键字:浏览器 时区 字符串 获取 Javascript      更新时间:2023-09-26

我想在我的网站上显示用户时区的全名。例如:

Eastern Standard Time (North America)
Pacific Daylight Time (North America)
West Africa Time

如何在 Javascript 中执行此操作?我见过呈现如下内容的解决方案:America/New_York .但这不是我真正想要的。

一行:

new window.Intl.DateTimeFormat().resolvedOptions().timeZone

您似乎要求在当前时间点以用户的当前语言对用户的当前时区进行人类可读的描述。

在大多数完全支持 ECMAScript 国际化 API 的现代浏览器和其他环境中,最好按如下方式提取:

// Get a specific point in time (here, the current date/time):
const d = new Date();
// Get a DateTimeFormat object for the user's current culture (via undefined)
// Ask specifically for the long-form of the time zone name in the options
const dtf = Intl.DateTimeFormat(undefined, {timeZoneName: 'long'});
// Format the date to parts, and pull out the value of the time zone name
const result = dtf.formatToParts(d).find((part) => part.type == 'timeZoneName').value;

例如,在冬季Windows上的Chrome 79浏览器中,它返回"太平洋标准时间"。 夏季的相同代码将返回"太平洋夏令时间"。 如果要反映在一年中的特定时间生效的时区说明,请在该特定时间创建Date对象。

在不支持 Intl API 的旧环境中,可以尝试从Date.toString输出中提取部分时区名称,如下所示:

var s = new Date().toString().match(/'((.*)')/).pop();

这之所以有效,是因为 Date 对象上 toString 函数的输出留给实现来定义,并且许多实现碰巧在括号中提供时区,如下所示:

Sun Feb 21 2016 22:11:00 GMT-0800 (Pacific Standard Time)

如果您正在寻找一个通用名称,例如简单的"太平洋时间" - 对不起,这不可用。

一种方法是使用 momentJs 库。

http://momentjs.com/

首先在您的页面中安装/导入momentjs。 有了这个,你可以得到UTC的时间。现在,从UTC开始,您可以使用momentJS时区转换为客户端的本地时间或任何其他时区。

http://momentjs.com/timezone/


更新 2

抱歉,上述库暂时无法检测到时区。

用了这个,它似乎对我有用。

<body>
<div id="testArea"></div>
<script type="text/javascript">
        var counter = 1;
        var interval = setInterval(function () {
            document.getElementById('testArea').innerHTML = counter + ": " + jstz.determine().name() + "<br/>";
            counter++;
        }, 2000);
</script>
</body>

存储库在这里下载并尝试下载存储库后,将其提取并进入实用程序文件夹并打开 index.html.

:https://bitbucket.org/pellepim/jstimezonedetect/downloads

显示示例演示的页面如下所示:

http://pellepim.bitbucket.org/jstz/