javascript 使用 moment.js 检测当前用户时区的 ID

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19420582/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 15:31:58  来源:igfitidea点击:

Detect the ID of the current user timezone using moment.js

javascripttimezonemomentjs

提问by Denys Séguret

What I'm looking for is a way to detect the browser's timezone ID (as defined in the Olson tables) but I don't care for the exact ID, I just need the ID of a timezone that works the same as the user's one (for example "Europe/Rome" is fine if the user is in Paris).

我正在寻找的是一种检测浏览器时区 ID(在Olson 表中定义)的方法,但我不关心确切的 ID,我只需要与用户的时区工作相同的时区的 ID (例如,如果用户在巴黎,“欧洲/罗马”就可以了)。

I'm not interested in the current offset, I really need the timezone so that I can send it to the server to do computations for other dates (the server has the Olson tables too).

我对当前的偏移量不感兴趣,我真的需要时区,以便我可以将它发送到服务器来计算其他日期(服务器也有 Olson 表)。

Theoretically, as I already use Moment.js timezone libraryand have included the Olson tables, I don't need anything else, but I don't find any API to do the detection. I don't know if it's hidden somewhere or if somebody has it already written. One of the problems is that the current timezone plugin seems to keep its data private.

从理论上讲,由于我已经使用Moment.js 时区库并包含 Olson 表,因此我不需要其他任何东西,但我没有找到任何 API 来进行检测。我不知道它是否隐藏在某处,或者是否有人已经写好了。问题之一是当前的时区插件似乎将其数据保密。

I dont'want a solution based on the integration of yet another copy or extract of the Olson tables (which I would have to maintain), I know there are a few libraries duplicating them, I want to use the ones I already have in Moment.js.

想要基于 Olson 表的另一个副本或摘录(我必须维护)的集成的解决方案,我知道有一些库复制它们,我想使用我在 Moment 中已有的库.js。

采纳答案by Anthony Chuinard

moment now has the guess()API as described here

现在有此处描述guess()API

回答by Denys Séguret

I made a small script to do that detection. It starts by registering the ids of the available timezones, then, on a call to the matchesfunction tests all timezone ids for the current time and the times 4 and 8 months later (to filter out the timezones with different daylight rules) and five years before.

我制作了一个小脚本来进行检测。它首先注册可用时区的 id,然后调用该matches函数测试当前时间和 4 个月和 8 个月后的所有时区 id(以过滤掉具有不同日光规则的时区)和五年前.

Here it is :

这里是 :

<script src="moment-with-langs.min.js"></script>
<script src="moment-timezone.min.js"></script>
<script src="moment-timezone-data.js"></script>
<script>
var tzdetect = {
    names: moment.tz.names(),
    matches: function(base){
        var results = [], now = Date.now(), makekey = function(id){
            return [0, 4, 8, -5*12, 4-5*12, 8-5*12, 4-2*12, 8-2*12].map(function(months){
                var m = moment(now + months*30*24*60*60*1000);
                if (id) m.tz(id);
                return m.format("DDHHmm");
            }).join(' ');
        }, lockey = makekey(base);
        tzdetect.names.forEach(function(id){
            if (makekey(id)===lockey) results.push(id);
        });
        return results;
    }
};
</script>

If you just want one timezone id, simply use

如果您只想要一个时区 ID,只需使用

var tzid = tzdetect.matches()[0];

Demonstration

示范

GitHub Repository : https://github.com/Canop/tzdetect.js

GitHub 存储库:https: //github.com/Canop/tzdetect.js

Update :The code here shown isn't compatible with the most recent versions of moment.js. Please refer to the GitHub repositoryfor a maintained (free to use) code.

更新:此处显示的代码与最新版本的 moment.js 不兼容。请参阅GitHub 存储库以获取维护(免费使用)代码。

2017 Update:There's now an API in moment.js to guess the timezone. That's probably the best solution right now.

2017 年更新:moment.js 现在有一个 API 来猜测时区。这可能是目前最好的解决方案。

回答by Denys Séguret

If you want to use the standard JavaScript API, you can use Intl.DateTimeFormat.resolvedOptionswhere there is browser support:

如果你想使用标准的 JavaScript API,你可以Intl.DateTimeFormat.resolvedOptions在有浏览器支持的地方使用:

Intl.DateTimeFormat().resolvedOptions().timeZone; // "America/Los_Angeles"

resolvedOptionsis currently (Jan 2016) available in all browsers except Safari on iOS and desktop: http://caniuse.com/#feat=internationalization

resolvedOptions目前(2016 年 1 月)可用于除 iOS 和桌面上的 Safari 之外的所有浏览器:http: //caniuse.com/#feat=internationalization

However, the timeZoneproperty is currently only available on Chrome.

但是,该timeZone属性目前仅在 Chrome 上可用

回答by Alex

There's a javascript tool that does just that :

有一个 javascript 工具可以做到这一点:

https://github.com/entraigas/jstz

https://github.com/entragas/jstz

It seems to deal with timezones ambiguity also.

它似乎也处理时区歧义。

Combined with momentJS timezone, you can get the timezone and show formatted date :

结合momentJS时区,可以获得时区并显示格式化日期:

var tzObj = jstz.determine();
var timezoneCode = tzObj.name();
console.log(moment.tz(timeZoneCode).format());