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

我两者都需要:

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


当前回答

用getTimezoneOffset ()

你可以像这样在几分钟内得到时区偏移量:

var offset = new Date().getTimezoneOffset(); console.log(抵消); //如果偏移量等于-60,则时区偏移量为UTC+01

时区偏移量是UTC和本地时间之间的差值,单位为分钟。注意,这意味着如果本地时区落后于UTC,则偏移量为正,如果落后于UTC,则偏移量为负。例如,如果您的时区是UTC+10(澳大利亚东部标准时间),则将返回-600。即使对于给定的区域,夏令时也可以防止此值为常量

Mozilla日期对象引用

请注意,并非所有时区都被整小时抵消:例如,纽芬兰是UTC减去3h 30m(将日光节约时间排除在等式之外)。

请注意,这只给你时区偏移(例如:UTC+01),它不给你时区(例如:欧洲/伦敦)。

其他回答

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

时区(小时)-

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和本地时间之间的差值(以分钟为单位)。

在新的Date()中,你可以获得偏移量,要获得时区名称,你可以这样做:

.replace .toString新的日期()() (/(.*\((.*)\).*)/, '$ 2》);

在日期的末尾得到between()值,即时区的名称。

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

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