如何收集访问者的时区信息?
我两者都需要:
时区(例如,欧洲/伦敦) 与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))
其他回答
这个就行了。
var time = new Date(),
timestamp = Date(1000 + time.getTime());
console.log(timestamp);
Thu May 25 2017 21:35:14 GMT+0300 (IDT)
未定义的
它已经回答了如何以分钟为单位获得一个整数的偏移量,但如果有人想要本地格林尼治标准时间偏移量作为字符串,例如。“+ 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))
作为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)
你只需要包含moment.js和jstz.js
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jstimezonedetect/1.0.6/jstz.min.js"></script>
在那之后
<script>
$(function(){
var currentTimezone = jstz.determine();
var timezone = currentTimezone.name();
alert(timezone);
});
</script>