Getting the client's timezone offset in JavaSc

2018-12-31 01:40发布

How can I gather the visitor's time zone information? I need the Timezone, as well as the GMT offset hours.

23条回答
浮光初槿花落
2楼-- · 2018-12-31 02:09

As an alternative to new Date().getTimezoneOffset() and moment().format('zz'), you can also use :

var offset = moment.parseZone(Date.now()).utcOffset() / 60
console.log(offset);
<script src="https://cdn.jsdelivr.net/momentjs/2.13.0/moment.min.js"></script>

jstimezone is also quite buggy and unmaintained (https://bitbucket.org/pellepim/jstimezonedetect/issues?status=new&status=open)

查看更多
妖精总统
3楼-- · 2018-12-31 02:10

Using an offset to calculate Timezone is a wrong approach, and you will always encounter problems. Time zones and daylight saving rules may change on several occasions during a year, and It's difficult to keep up with changes.

To get a correct timezone in JavaScript, you should use

console.log(Intl.DateTimeFormat().resolvedOptions().timeZone)

Unfortunately, by the time of writing this, it's not yet widely supported.
I know it's working correctly at least in Chrome.

ecma-402/1.0 says that timeZone may be undefined if not provided to constructor. However, future draft (3.0) fixed that issue by changing to system default timezone.

In this version of the ECMAScript Internationalization API, the timeZone property will remain undefined if no timeZone property was provided in the options object provided to the Intl.DateTimeFormat constructor. However, applications should not rely on this, as future versions may return a String value identifying the host environment’s current time zone instead.

in ecma-402/3.0 which is still in a draft it changed to

In this version of the ECMAScript 2015 Internationalization API, the timeZone property will be the name of the default time zone if no timeZone property was provided in the options object provided to the Intl.DateTimeFormat constructor. The previous version left the timeZone property undefined in this case.

So before using it check current support across browsers for example at:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat/resolvedOptions

查看更多
心情的温度
4楼-- · 2018-12-31 02:10

try getTimezoneOffset() of the Date object:

var curdate = new Date()
var offset = curdate.getTimezoneOffset()

This method returns time zone offset in minutes which is the difference between GMT and local time in minutes.

查看更多
泪湿衣
5楼-- · 2018-12-31 02:10

JavaScript:

var d = new Date();
var n = d.getTimezoneOffset();
var timezone = n / -60;
console.log(timezone);

查看更多
美炸的是我
6楼-- · 2018-12-31 02:13

Use this to convert OffSet to postive:

var offset = new Date().getTimezoneOffset();
console.log(offset);
this.timeOffSet = offset + (-2*offset);
console.log(this.timeOffSet);
查看更多
登录 后发表回答