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

我两者都需要:

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


当前回答

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

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

其他回答

这可能不是最优雅的解决方案,但却是最通用的。

这使用了Intl的timeZoneName属性。DateTimeFormat

function getTimeZone(zoneName = "long") { // set up formatter let formatter = new Intl.DateTimeFormat(undefined, { timeZoneName: zoneName }); // run formatter on current date return formatter.formatToParts(Date.now()) // extract the actual value from the formatter, only reliable way i can find to do this .find(formatted => formatted.type === "timeZoneName")['value']; } // console.log every type for (const zoneName of ['short', 'long', 'shortOffset', 'longOffset', 'shortGeneric', 'longGeneric']) { console.log(`${zoneName}: ${getTimeZone(zoneName)}`) } /* short: CDT long: Central Daylight Time shortOffset: GMT-5 longOffset: GMT-05:00 shortGeneric: CT longGeneric: Central Time */

这不仅得到格式化的GMT偏移时间(即GMT-5),还得到时区的口语化名称(即中央日光时间)。

这个方法唯一不做的是获取IANA时区。我推荐上面的答案。

据我所知,DateTimeFormat没有自定义格式化的方法,因此使用formattpart,这似乎是获得时区的唯一可靠方法。

值得注意的是,目前的ECMAscript规范中只有short和long被正式定义,其他4个选项只是标准提议的一部分,在撰写本文时,safari中明显没有,尽管它正在进行中

尝试Date对象的getTimezoneOffset():

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

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

试试这个:

new Date().toLocaleString("en-US",Intl.DateTimeFormat().resolvedOptions().timeZone)

这将在客户端的浏览器上查找timeZone。

一旦我有了这个“简单”的任务,我使用(new Date()). gettimezoneoffset() -这里广泛建议的方法。但事实证明,这个解决方案并不完全正确。 在我的例子中,由于一些未记录的原因,new Date()返回GMT+0200,而new Date(0)返回GMT+0300,这是正确的。从那时起我就一直用

(new Date(0)). gettimezoneoffset()来获得正确的时间差。

moment.js:

moment().format('zz');