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

我两者都需要:

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


当前回答

下面是通过将时区传递给函数来查找远程国家TimezoneOffset的解决方案。在这个例子中,'Asia/Calcutta'是时区

function getTimezoneOffset(timezone) {
    LocalDate = new Date();
    LocalDate.setMilliseconds(0);

    const LocalOffset = LocalDate.getTimezoneOffset();
    RemoteLocaleStr = LocalDate.toLocaleString('en-US', {timeZone: timezone});
    RemoteDate = new Date(RemoteLocaleStr);
    diff = (LocalDate.getTime()-RemoteDate.getTime()) / 1000 / 60 ;

    RemoteOffset = LocalOffset + diff;
    return RemoteOffset;
}
console.log(getTimezoneOffset('Asia/Calcutta'));

其他回答

这对我来说是很好的工作:

// Translation to offset in Unix Timestamp
let timeZoneOffset = ((new Date().getTimezoneOffset())/60)*3600;

时区(小时)-

var offset = new Date().getTimezoneOffset(); 如果(抵消< 0) console.log("您的时区是- GMT+" + (offset/-60)); 其他的 console.log("您的时区是- GMT-" + offset/60);

如果你想要像你在评论中提到的那样精确,那么你应该这样尝试-

var offset = new Date().getTimezoneOffset(); 如果(偏移<0) { var extraZero = “”; if(-offset%60<10) extraZero=“0”; console.log( “Your timezone is- GMT+” + Math.ceil(offset/-60)+“:”+extraZero+(-offset%60)); } 还 { var extraZero = “”; if(偏移量%60<10) extraZero=“0”; console.log( “Your timezone is- GMT-” + Math.floor(offset/60)+“:”+extraZero+(offset%60)); }

尝试Date对象的getTimezoneOffset():

var curdate = new Date()
var offset = curdate.getTimezoneOffset()

此方法返回时区偏移量(以分钟为单位),即GMT和本地时间之间的差值(以分钟为单位)。

编辑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库来提供时区支持。

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

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