Javascript 从浏览器获取客户端时区

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6939685/
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-08-23 23:51:46  来源:igfitidea点击:

get client time zone from browser

javascripthttpbrowsertimezone

提问by confucius

Is there a reliable way to get a timezone from client browser? I saw the following links but I want a more robust solution.

有没有可靠的方法从客户端浏览器获取时区?我看到了以下链接,但我想要一个更强大的解决方案。

Auto detect a time zone with JavaScript

使用 JavaScript 自动检测时区

Timezone detection in JavaScript

JavaScript 中的时区检测

采纳答案by Georgian Citizen

Look at this repository pageloomit is helpful

看看这个存储库pageloom它是有帮助的

download jstz.min.js and add a function to your html page

下载 jstz.min.js 并向您的 html 页面添加一个函数

<script language="javascript">
    function getTimezoneName() {
        timezone = jstz.determine()
        return timezone.name();
    }
</script>

and call this function from your display tag

并从您的显示标签调用此函数

回答by Wallace

Half a decade later we have a built-in way for it! For modern browsers I would use:

五年后,我们有一个内置的方法!对于现代浏览器,我会使用:

const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
console.log(tz);

This returns a IANA timezone string, but not the offset. Learn more at the MDN reference.

这将返回 IANA 时区字符串,但不返回偏移量。在MDN 参考 中了解更多信息

Compatibility table- as of March 2019, works for 90% of the browsers in use globally. Doesn't work on Internet Explorer.

兼容性表- 截至 2019 年 3 月,适用于全球 90% 的浏览器。不适用于 Internet Explorer

回答by Chris W.

Often when people are looking for "timezones", what will suffice is just "UTC offset". e.g., their server is in UTC+5 and they want to know that their client is running in UTC-8.

通常当人们寻找“时区”时,只需要“UTC 偏移量”就足够了。例如,他们的服务器在 UTC+5 并且他们想知道他们的客户端在 UTC-8 中运行



In plain old javascript (new Date()).getTimezoneOffset()/60will return the current number of hours offset from UTC.

在普通的旧 javascript 中,(new Date()).getTimezoneOffset()/60将返回从 UTC 偏移的当前小时数。

It's worth noting a possible "gotcha" in the sign of the getTimezoneOffset()return value (from MDN docs):

值得注意的是,getTimezoneOffset()返回值的符号中可能存在“陷阱” (来自 MDN 文档)

The time-zone offset is the difference, in minutes, between UTC and local time. Note that this means that the offset is positive if the local timezone is behind UTC and negative if it is ahead. For example, for time zone UTC+10:00 (Australian Eastern Standard Time, Vladivostok Time, Chamorro Standard Time), -600 will be returned.

时区偏移量是 UTC 和本地时间之间的差异(以分钟为单位)。请注意,这意味着如果本地时区落后于 UTC,则偏移量为正,如果领先则为负。例如,对于时区 UTC+10:00(澳大利亚东部标准时间、符拉迪沃斯托克时间、查莫罗标准时间),将返回 -600。



However, I recommend you use the day.jsfor time/date related Javascript code. In which case you can get an ISO 8601 formatted UTC offset by running:

但是,我建议您将day.js用于与时间/日期相关的 Javascript 代码。在这种情况下,您可以通过运行获得 ISO 8601 格式的 UTC 偏移量:

> dayjs().format("Z")
"-08:00"

It probably bears mentioning that the client can easily falsify this information.

值得一提的是,客户很容易伪造这些信息。

(Note: this answer originally recommended https://momentjs.com/, but dayjs is a more modern, smaller alternative.)

(注意:这个答案最初推荐https://momentjs.com/,但 dayjs 是一个更现代、更小的替代方案。)

回答by Johannes Hoff

For now, the best bet is probably jstz as suggested in mbayloon's answer.

目前,最好的选择可能是mbayloon's answer 中建议的jstz

For completeness, it should be mentioned that there is a standard on it's way: Intl. You can see this in Chrome already:

为了完整起见,应该提到它的方式有一个标准:Intl。您已经可以在 Chrome 中看到这一点:

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

(This doesn't actually follow the standard, which is one more reason to stick with the library)

(这实际上并不遵循标准,这是坚持使用库的另一个原因)

回答by Pushkar Newaskar

Here is a jsfiddle

这是一个jsfiddle

It provides the abbreviation of the current user timezone.

它提供了当前用户时区的缩写。

Here is the code sample

这是代码示例

var tz = jstz.determine();
console.log(tz.name());
console.log(moment.tz.zone(tz.name()).abbr(new Date().getTime()));

回答by Tomas Tomecek

you could use moment-timezoneto guess the timezone:

您可以使用moment-timezone来猜测时区:

> moment.tz.guess()
"America/Asuncion"

回答by David R Tribble

I used an approach similar to the one taken by Josh Fraser, which determines the browser time offset from UTC and whether it recognizes DST or not (but somewhat simplified from his code):

我使用了一种类似于Josh Fraser采用的方法,它确定浏览器与 UTC 的时间偏移以及它是否识别 DST(但从他的代码中稍微简化了一些):

var ClientTZ = {
    UTCoffset:  0,          // Browser time offset from UTC in minutes
    UTCoffsetT: '+0000S',   // Browser time offset from UTC in '±hhmmD' form
    hasDST:     false,      // Browser time observes DST

    // Determine browser's timezone and DST
    getBrowserTZ: function () {
        var self = ClientTZ;

        // Determine UTC time offset
        var now = new Date();
        var date1 = new Date(now.getFullYear(), 1-1, 1, 0, 0, 0, 0);    // Jan
        var diff1 = -date1.getTimezoneOffset();
        self.UTCoffset = diff1;

        // Determine DST use
        var date2 = new Date(now.getFullYear(), 6-1, 1, 0, 0, 0, 0);    // Jun
        var diff2 = -date2.getTimezoneOffset();
        if (diff1 != diff2) {
            self.hasDST = true;
            if (diff1 - diff2 >= 0)
                self.UTCoffset = diff2;     // East of GMT
        }

        // Convert UTC offset to ±hhmmD form
        diff2 = (diff1 < 0 ? -diff1 : diff1) / 60;
        var hr = Math.floor(diff2);
        var min = diff2 - hr;
        diff2 = hr * 100 + min * 60;
        self.UTCoffsetT = (diff1 < 0 ? '-' : '+') + (hr < 10 ? '0' : '') + diff2.toString() + (self.hasDST ? 'D' : 'S');

        return self.UTCoffset;
    }
};

// Onload
ClientTZ.getBrowserTZ();

Upon loading, the ClientTZ.getBrowserTZ()function is executed, which sets:

加载后,ClientTZ.getBrowserTZ()函数被执行,它设置:

  • ClientTZ.UTCoffsetto the browser time offset from UTC in minutes (e.g., CST is ?360 minutes, which is ?6.0 hours from UTC);
  • ClientTZ.UTCoffsetTto the offset in the form '±hhmmD'(e.g., '-0600D'), where the suffix is Dfor DST and Sfor standard (non-DST);
  • ClientTZ.hasDST(to true or false).
  • ClientTZ.UTCoffset以分钟为单位与 UTC 的浏览器时间偏移量(例如,CST 为 360 分钟,即 UTC 的 6.0 小时);
  • ClientTZ.UTCoffsetT到格式'±hhmmD'(例如,'-0600D')中的偏移量,其中后缀D用于 DST 和S标准(非 DST);
  • ClientTZ.hasDST(真或假)。

The ClientTZ.UTCoffsetis provided in minutes instead of hours, because some timezones have fractional hourly offsets (e.g., +0415).

ClientTZ.UTCoffset在几分钟而不是几小时提供,因为时区的一些有分数每小时偏移量(例如,0415)。

The intent behind ClientTZ.UTCoffsetTis to use it as a key into a table of timezones (not provided here), such as for a drop-down <select>list.

背后的意图ClientTZ.UTCoffsetT是将其用作时区表(此处未提供)的键,例如用于下拉<select>列表。

回答by Florian Margaine

No. There is no single reliable way and there will never be. Did you really think you could trust the client?

不。没有唯一可靠的方法,永远不会有。你真的认为你可以信任客户吗?