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

我两者都需要:

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


当前回答

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

其他回答

将OffSet转换为正数:

var offset = new Date().getTimezoneOffset();
console.log(offset);
this.timeOffSet = offset + (-2*offset);
console.log(this.timeOffSet);

试试这个,

new Date().toString().split("GMT")[1].split(" (")[0]

为什么不直接使用:

function timezoneOffset(date: Date) {
  return 6000 * ((date.getUTCHours() - date.getHours()) * 60 + ((date.getUTCMinutes() - date.getMinutes())))
}

你只需要包含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>

作为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)