如何收集访问者的时区信息?
我两者都需要:
时区(例如,欧洲/伦敦) 与UTC或GMT的偏移(例如,UTC+01)
如何收集访问者的时区信息?
我两者都需要:
时区(例如,欧洲/伦敦) 与UTC或GMT的偏移(例如,UTC+01)
当前回答
如果你只需要“MST”或“EST”时区缩写:
函数getTimeZone () { var now = new Date().toString(); var timeZone = now.replace(/.*[(](.*)[)].*/,'$1') 返回时区; } console.log (getTimeZone ());
其他回答
使用偏移量来计算时区是一种错误的方法,您总是会遇到问题。时区和夏令时规则可能会在一年中发生几次变化,并且很难跟上变化。
要获得JavaScript格式的系统IANA时区,您应该使用
控制台日志(Intl DateTimeFormat resolvedOptions()()。timeZone)
截至2023年2月,全球93.75%的浏览器都能正常运行。
旧的兼容性信息
ecma-402/1.0说timeZone如果没有提供给构造函数,可能是未定义的。然而,未来的草案(3.0)通过更改系统默认时区修复了这个问题。
在此版本的ECMAScript国际化API中, 如果没有timeZone属性,则timeZone属性将保持未定义 提供在提供给Intl的options对象中。DateTimeFormat 构造函数。但是,应用程序不应该依赖于此,因为未来 版本可能返回一个String值,用于标识主机环境 改为当前时区。
在ecma-402/3.0草案中,它被改成了
在此版本的ECMAScript 2015国际化API中 如果没有,timeZone属性将是默认时区的名称 属性在options对象中提供 Intl。DateTimeFormat构造函数。上一版本的 timeZone属性在本例中未定义。
这可能不是最优雅的解决方案,但却是最通用的。
这使用了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中明显没有,尽管它正在进行中
正如其他人提到的,要获得时区:
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))
这个值来自用户的机器,可以随时更改,所以我认为没关系,我只是想获得一个近似值,然后在我的服务器上将其转换为GMT。
例如,我来自台湾,它为我返回“+8”。
工作示例
JS
function timezone() {
var offset = new Date().getTimezoneOffset();
var minutes = Math.abs(offset);
var hours = Math.floor(minutes / 60);
var prefix = offset < 0 ? "+" : "-";
return prefix+hours;
}
$('#result').html(timezone());
HTML
<div id="result"></div>
结果
+8
它已经回答了如何以分钟为单位获得一个整数的偏移量,但如果有人想要本地格林尼治标准时间偏移量作为字符串,例如。“+ 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))