从浏览器获取客户端时区

发布于 2024-11-27 15:21:57 字数 319 浏览 0 评论 0原文

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

使用 JavaScript 自动检测时区< /a>

JavaScript 中的时区检测

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

Timezone detection in JavaScript

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

久伴你 2024-12-04 15:21:57

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

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

这会返回 IANA 时区字符串,但不是偏移量。如需了解更多信息,请访问 MDN 参考

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

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.

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

一笔一画续写前缘 2024-12-04 15:21:57

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


在普通的旧式 JavaScript 中,(new Date()).getTimezoneOffset()/60 将返回当前与 UTC 的小时数。

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

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


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

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

值得一提的是,客户端可以轻松伪造此信息。

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

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.


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

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

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.


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

> 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.)

老子叫无熙 2024-12-04 15:21:57

看看这个存储库 pageloom 它很有帮助,

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

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

,然后从您的显示标签调用此函数

Look at this repository pageloom it is helpful

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

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

and call this function from your display tag

も星光 2024-12-04 15:21:57

目前,最好的选择可能是 jstz,如 mbayloon 的答案。

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

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

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

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

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

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

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

鲜血染红嫁衣 2024-12-04 15:21:57

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

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

you could use moment-timezone to guess the timezone:

> moment.tz.guess()
"America/Asuncion"
一江春梦 2024-12-04 15:21:57

这里有一个 jsfiddle

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

这是代码示例

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

Here is a 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()));
怪我太投入 2024-12-04 15:21:57

我使用了一种类似于 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();

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

  • ClientTZ.UTCoffset 为浏览器与 UTC 的时间偏移(以分钟为单位)(例如,CST 为 −360 分钟,距 UTC 为 −6.0 小时);
  • ClientTZ.UTCoffsetT'±hhmmD' 形式的偏移量(例如 '-0600D'),其中后缀为 D 代表 DST,S 代表标准(非 DST);
  • ClientTZ.hasDST(true 或 false)。

ClientTZ.UTCoffset 以分钟而不是小时为单位提供,因为某些时区具有小数小时偏移量(例如,+0415)。

ClientTZ.UTCoffsetT 背后的目的是将其用作时区表(此处未提供)的键,例如下拉

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):

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.UTCoffset to the browser time offset from UTC in minutes (e.g., CST is −360 minutes, which is −6.0 hours from UTC);
  • ClientTZ.UTCoffsetT to the offset in the form '±hhmmD' (e.g., '-0600D'), where the suffix is D for DST and S for standard (non-DST);
  • ClientTZ.hasDST (to true or false).

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

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

萌︼了一个春 2024-12-04 15:21:57

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文