如何收集访问者的时区信息?
我两者都需要:
时区(例如,欧洲/伦敦) 与UTC或GMT的偏移(例如,UTC+01)
如何收集访问者的时区信息?
我两者都需要:
时区(例如,欧洲/伦敦) 与UTC或GMT的偏移(例如,UTC+01)
当前回答
如果你只需要“MST”或“EST”时区缩写:
函数getTimeZone () { var now = new Date().toString(); var timeZone = now.replace(/.*[(](.*)[)].*/,'$1') 返回时区; } console.log (getTimeZone ());
其他回答
试试这个,
new Date().toString().split("GMT")[1].split(" (")[0]
时区(小时)-
var offset = new Date().getTimezoneOffset(); 如果(抵消< 0) console.log("您的时区是- GMT+" + (offset/-60)); 其他的 console.log("您的时区是- GMT-" + offset/60);
如果你想要像你在评论中提到的那样精确,那么你应该这样尝试-
var offset = new Date().getTimezoneOffset(); 如果(偏移<0) { var extraZero = “”; if(-offset%60<10) extraZero=“0”; console.log( “Your timezone is- GMT+” + Math.ceil(offset/-60)+“:”+extraZero+(-offset%60)); } 还 { var extraZero = “”; if(偏移量%60<10) extraZero=“0”; console.log( “Your timezone is- GMT-” + Math.floor(offset/60)+“:”+extraZero+(offset%60)); }
尝试Date对象的getTimezoneOffset():
var curdate = new Date()
var offset = curdate.getTimezoneOffset()
此方法返回时区偏移量(以分钟为单位),即GMT和本地时间之间的差值(以分钟为单位)。
在新的Date()中,你可以获得偏移量,要获得时区名称,你可以这样做:
.replace .toString新的日期()() (/(.*\((.*)\).*)/, '$ 2》);
在日期的末尾得到between()值,即时区的名称。
你可以使用:
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();
浏览器时区检测是相当棘手的,因为浏览器提供的信息很少。
Moment Timezone在当年的一些时刻上使用Date.getTimezoneOffset()和Date.toString()来收集尽可能多的关于浏览器环境的信息。然后将该信息与加载的所有时区数据进行比较,并返回最接近的匹配。如果存在重叠,则返回人口最多的城市所在的时区。
console.log(moment.tz.guess()); // America/Chicago