如何收集访问者的时区信息?
我两者都需要:
时区(例如,欧洲/伦敦) 与UTC或GMT的偏移(例如,UTC+01)
如何收集访问者的时区信息?
我两者都需要:
时区(例如,欧洲/伦敦) 与UTC或GMT的偏移(例如,UTC+01)
当前回答
这就是我的解决方案:
// For time zone:
const timeZone = /\((.*)\)/.exec(new Date().toString())[1];
// Offset hours:
const offsetHours = new Date().getTimezoneOffset() / 60;
console.log(`${timeZone}, ${offsetHours}hrs`);
其他回答
这可能不是最优雅的解决方案,但却是最通用的。
这使用了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中明显没有,尽管它正在进行中
编辑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库来提供时区支持。
作为new Date().getTimezoneOffset()和moment().format('zz')的替代方案,你也可以使用momentjs:
var offset = moment.parseZone(Date.now()).utcOffset() / 60 . var offset = moment.parseZone(Date.now()).utcOffset( console.log(抵消); < script src = " https://cdn.jsdelivr.net/momentjs/2.13.0/moment.min.js " > < /脚本>
Jstimezone也有很多bug,而且没有维护(https://bitbucket.org/pellepim/jstimezonedetect/issues?status=new&status=open)
将OffSet转换为正数:
var offset = new Date().getTimezoneOffset();
console.log(offset);
this.timeOffSet = offset + (-2*offset);
console.log(this.timeOffSet);
正如其他人提到的,要获得时区:
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))