如何收集访问者的时区信息?
我两者都需要:
时区(例如,欧洲/伦敦) 与UTC或GMT的偏移(例如,UTC+01)
如何收集访问者的时区信息?
我两者都需要:
时区(例如,欧洲/伦敦) 与UTC或GMT的偏移(例如,UTC+01)
当前回答
它已经回答了如何以分钟为单位获得一个整数的偏移量,但如果有人想要本地格林尼治标准时间偏移量作为字符串,例如。“+ 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))
其他回答
为什么不直接使用:
function timezoneOffset(date: Date) {
return 6000 * ((date.getUTCHours() - date.getHours()) * 60 + ((date.getUTCMinutes() - date.getMinutes())))
}
它已经回答了如何以分钟为单位获得一个整数的偏移量,但如果有人想要本地格林尼治标准时间偏移量作为字符串,例如。“+ 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))
正如其他人提到的,要获得时区:
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))
使用momentjs,您可以找到当前时区为
console.log(时刻).utcOffset ());//(-240, -120, - 60,0, 60,120, 240,等等) < script src = " https://cdn.jsdelivr.net/momentjs/2.13.0/moment.min.js " > < /脚本>
使用dayjs,您可以找到当前时区为
console.log(dayjs().utcOffset());(-240、-120、-60、0、60、120、240 等) <script src=“https://unpkg.com/dayjs@1.8.10/dayjs.min.js”></script>
这两个API都返回以分钟为单位的utc偏移量。
现在医生 Dayjs医生
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