如何收集访问者的时区信息?
我两者都需要:
时区(例如,欧洲/伦敦) 与UTC或GMT的偏移(例如,UTC+01)
如何收集访问者的时区信息?
我两者都需要:
时区(例如,欧洲/伦敦) 与UTC或GMT的偏移(例如,UTC+01)
当前回答
moment.js:
moment().format('zz');
其他回答
moment.js:
moment().format('zz');
使用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医生
这对我来说是很好的工作:
// Translation to offset in Unix Timestamp
let timeZoneOffset = ((new Date().getTimezoneOffset())/60)*3600;
正如其他人提到的,要获得时区:
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))
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;
}
示例:2018年6月21日星期四18:12:50 GMT+0530(印度标准时间)
O/P: +0530