如何收集访问者的时区信息?

我两者都需要:

时区(例如,欧洲/伦敦) 与UTC或GMT的偏移(例如,UTC+01)


当前回答

正如其他人提到的,要获得时区:

const tz = Intl.DateTimeFormat().resolvedOptions().timeZone

之前没有提到,要从时区获取偏移量,使用区域设置“ia”(参见https://stackoverflow.com/a/64262840/1061871)

const getOffset = (tz) => Intl.DateTimeFormat("ia", {
                timeZoneName: "shortOffset",
                timeZone : tz
              })
                .formatToParts()
                .find((i) => i.type === "timeZoneName").value // => "GMT+/-hh:mm"
                .slice(3); //=> +/-hh:mm

 console.log(tz + ' UTC' + getOffset(tz))


 

其他回答

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat

Intl. datetimeformat()构造函数创建Intl. datetimeformat。启用对语言敏感的日期和时间格式化的DateTimeFormat对象。

Intl.DateTimeFormat().resolvedOptions().timeZone // Asia/Kolkata

它已经回答了如何以分钟为单位获得一个整数的偏移量,但如果有人想要本地格林尼治标准时间偏移量作为字符串,例如。“+ 1130”:

function pad(number, length){
    var str = "" + number
    while (str.length < length) {
        str = '0'+str
    }
    return str
}

var offset = new Date().getTimezoneOffset()
offset = ((offset<0? '+':'-')+ // Note the reversed sign!
          pad(parseInt(Math.abs(offset/60)), 2)+
          pad(Math.abs(offset%60), 2))

使用momentjs,您可以找到当前时区为

console.log(时刻).utcOffset ());//(-240, -120, - 60,0, 60,120, 240,等等) < script src = " https://cdn.jsdelivr.net/momentjs/2.13.0/moment.min.js " > < /脚本>


使用dayjs,您可以找到当前时区为

console.log(dayjs().utcOffset());(-240、-120、-60、0、60、120、240 等) <script src=“https://unpkg.com/dayjs@1.8.10/dayjs.min.js”></script>

这两个API都返回以分钟为单位的utc偏移量。

现在医生 Dayjs医生

正如其他人提到的,要获得时区:

const tz = Intl.DateTimeFormat().resolvedOptions().timeZone

之前没有提到,要从时区获取偏移量,使用区域设置“ia”(参见https://stackoverflow.com/a/64262840/1061871)

const getOffset = (tz) => Intl.DateTimeFormat("ia", {
                timeZoneName: "shortOffset",
                timeZone : tz
              })
                .formatToParts()
                .find((i) => i.type === "timeZoneName").value // => "GMT+/-hh:mm"
                .slice(3); //=> +/-hh:mm

 console.log(tz + ' UTC' + getOffset(tz))


 

编辑3-19-2022 -警告:我不再推荐这种方法,因为它在多个浏览器和地区有问题。

我意识到这个答案有点离题,但我想我们中的许多人在寻找答案时也想格式化显示的时区,也许还想获得时区的缩写。所以它开始了…

如果你想让客户端时区格式化得很好,你可以依赖JavaScript Date。toString方法,执行以下操作:

var split = new Date().toString().split(" ");
var timeZoneFormatted = split[split.length - 2] + " " + split[split.length - 1];

这将为您提供“GMT-0400 (EST)”,例如,包括适用的时区分钟。

或者,使用regex你可以提取任何想要的部分:

“GMT-0400 (EDT)”:

new Date().toString().match(/([A-Z]+[\+-][0-9]+.*)/)[1]

对于“GMT-0400”:

new Date().toString().match(/([A-Z]+[\+-][0-9]+)/)[1]

对于“EDT”:

new Date().toString().match(/\(([A-Za-z\s].*)\)/)[1]

对于“-0400”:

new Date().toString().match(/([-\+][0-9]+)\s/)[1]

日期。toString参考:https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/toString

编辑10/6/2020 -上述解决方案可能不适用于所有浏览器和地区。如果可能的话,我建议你使用date-fns、luxon或dayjs这样的javascript库来提供时区支持。