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 01:48

With moment.js:

moment().format('zz');
查看更多
唯独是你
3楼-- · 2018-12-31 01:48

With , you can find current timezone as

console.log(moment().utcOffset()); // (-240, -120, -60, 0, 60, 120, 240, etc.)
<script src="https://cdn.jsdelivr.net/momentjs/2.13.0/moment.min.js"></script>

It returns utc offset in minutes.

More Info

查看更多
荒废的爱情
4楼-- · 2018-12-31 01:50
function getLocalTimeZone() {
    var dd = new Date();
    var ddStr = dd.toString();
    var ddArr = ddStr.split(' ');
    var tmznSTr = ddArr[5];
    tmznSTr = tmznSTr.substring(3, tmznSTr.length);
    return tmznSTr;
}

Example : Thu Jun 21 2018 18:12:50 GMT+0530 (India Standard Time)

O/P : +0530

查看更多
还给你的自由
5楼-- · 2018-12-31 01:50

This is very good work for me:

// Translation to offset in Unix Timestamp
let timeZoneOffset = ((new Date().getTimezoneOffset())/60)*3600;
查看更多
公子世无双
6楼-- · 2018-12-31 01:51

var offset = new Date().getTimezoneOffset();
console.log(offset);

The time-zone offset is the difference, in minutes, between UTC and local time. Note that this means that the offset is positive if the local timezone is behind UTC and negative if it is ahead. For example, if your time zone is UTC+10 (Australian Eastern Standard Time), -600 will be returned. Daylight savings time prevents this value from being a constant even for a given locale

Note that not all timezones are offset by whole hours: for example, Newfoundland is UTC minus 3h 30m (leaving Daylight Saving Time out of the equation).

查看更多
只若初见
7楼-- · 2018-12-31 01:51

You can use:

moment-timezone

<script src="moment.js"></script>
<script src="moment-timezone-with-data.js"></script>

// retrieve timezone by name (i.e. "America/Chicago")
moment.tz.guess();

Browser time zone detection is rather tricky to get right, as there is little information provided by the browser.

Moment Timezone uses Date.getTimezoneOffset() and Date.toString() on a handful of moments around the current year to gather as much information about the browser environment as possible. It then compares that information with all the time zone data loaded and returns the closest match. In case of ties, the time zone with the city with largest population is returned.

console.log(moment.tz.guess()); // America/Chicago
查看更多
登录 后发表回答