从浏览器获取客户端时区[重复]

2020/11/17 07:42 · javascript ·  · 0评论

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

使用JavaScript自动检测时区

JavaScript中的时区检测

查看此存储库pageloom很有帮助

下载jstz.min.js并将功能添加到您的html页面

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

然后从您的显示代码调用此函数

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

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

这将返回IANA时区字符串,但不会返回offsetMDN参考中了解更多信息

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

通常,当人们在寻找“时区”时,仅需“ UTC偏移量”即可。例如,他们的服务器位于UTC + 5中,并且他们想知道其客户端正在UTC-8中运行


简而言之,旧的javascript(new Date()).getTimezoneOffset()/60会返回当前距UTC的小时数。

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

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


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

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

可能值得一提的是,客户可以轻易地伪造此信息。

(注意:此答案最初建议使用https://momentjs.com/,但dayjs是更现代,更小的选择。)

就目前而言,最好的选择可能是mbayloon的答案中建议的jstz

为了完整起见,应该提到的是有一个标准:Intl您已经可以在Chrome浏览器中看到此内容:

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

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

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

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

这是一个jsfiddle

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

这是代码示例

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

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.

Here is a version that works well in September 2020 using fetch and https://worldtimeapi.org/api

fetch("https://worldtimeapi.org/api/ip")
  .then(response => response.json())
  .then(data => console.log(data.timezone,data.datetime,data.dst));

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

本文地址:http://javascript.askforanswer.com/congliulanqihuoqukehuduanshiquzhongfu.html
文章标签: ,   ,   ,  
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!

文件下载

老薛主机终身7折优惠码boke112

上一篇:
下一篇:

评论已关闭!