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

我两者都需要:

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


当前回答

时区(小时)-

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)); }

其他回答

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

如果你只需要“MST”或“EST”时区缩写:

函数getTimeZone () { var now = new Date().toString(); var timeZone = now.replace(/.*[(](.*)[)].*/,'$1') 返回时区; } console.log (getTimeZone ());

正如其他人提到的,要获得时区:

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


 

在新的Date()中,你可以获得偏移量,要获得时区名称,你可以这样做:

.replace .toString新的日期()() (/(.*\((.*)\).*)/, '$ 2》);

在日期的末尾得到between()值,即时区的名称。

同时给出偏移量和时区的一行程序就是在一个新的Date对象上调用toTimeString()。中数:

toTimeString()方法以美国英语的人类可读形式返回Date对象的时间部分。

问题是时区不是标准的IANA格式;它比IANA“大洲/城市”格式更方便用户使用。试试吧:

.toTimeString console.log(新日期()().slice (9)); .resolvedOptions console.log (Intl.DateTimeFormat () () .timeZone); console.log(new Date().getTimezoneOffset() / -60);

现在在加利福尼亚,toTimeString()返回太平洋夏令时,而Intl API返回美国/洛杉矶。在哥伦比亚,你可以使用哥伦比亚标准时间,而不是美国/波哥大标准时间。

请注意,这个问题的许多其他答案都试图通过调用Date.toString()来获取相同的信息。这种方法并不可靠,正如MDN解释的那样:

Date instances refer to a specific point in time. Calling toString() will return the date formatted in a human readable form in American English. [...] Sometimes it is desirable to obtain a string of the time portion; such a thing can be accomplished with the toTimeString() method. The toTimeString() method is especially useful because compliant engines implementing ECMA-262 may differ in the string obtained from toString() for Date objects, as the format is implementation-dependent; simple string slicing approaches may not produce consistent results across multiple engines.