是否有一种标准的方法可以让服务器在网页中确定用户的时区?
可能来自HTTP报头或用户代理字符串的一部分?
是否有一种标准的方法可以让服务器在网页中确定用户的时区?
可能来自HTTP报头或用户代理字符串的一部分?
当前回答
这里有一种更完整的方法。
获取用户的时区偏移量 测试一些日子的夏令时边界,以确定它们是否在使用夏令时的区域。
节选如下:
function TimezoneDetect(){
var dtDate = new Date('1/1/' + (new Date()).getUTCFullYear());
var intOffset = 10000; //set initial offset high so it is adjusted on the first attempt
var intMonth;
var intHoursUtc;
var intHours;
var intDaysMultiplyBy;
// Go through each month to find the lowest offset to account for DST
for (intMonth=0;intMonth < 12;intMonth++){
//go to the next month
dtDate.setUTCMonth(dtDate.getUTCMonth() + 1);
// To ignore daylight saving time look for the lowest offset.
// Since, during DST, the clock moves forward, it'll be a bigger number.
if (intOffset > (dtDate.getTimezoneOffset() * (-1))){
intOffset = (dtDate.getTimezoneOffset() * (-1));
}
}
return intOffset;
}
从JS获取TZ和DST(通过Way Back Machine)
其他回答
试试下面的PHP代码:
<?php
$ip = $_SERVER['REMOTE_ADDR'];
$json = file_get_contents("http://api.easyjquery.com/ips/?ip=" . $ip . "&full=true");
$json = json_decode($json,true);
$timezone = $json['LocalTimeZone'];
?>
使用jQuery在AJAX请求上提交时区偏移量作为HTTP报头
$.ajaxSetup({
beforeSend: function(xhr, settings) {
xhr.setRequestHeader("X-TZ-Offset", -new Date().getTimezoneOffset()/60);
}
});
您还可以通过使用moment.tz.guess();从http://momentjs.com/timezone/docs/ # / using-timezones / guessing-user-timezone /
在PHP中获取有效的TZ数据库时区名称是一个两步过程:
With JavaScript, get timezone offset in minutes through getTimezoneOffset. This offset will be positive if the local timezone is behind UTC and negative if it is ahead. So you must add an opposite sign to the offset. var timezone_offset_minutes = new Date().getTimezoneOffset(); timezone_offset_minutes = timezone_offset_minutes == 0 ? 0 : -timezone_offset_minutes; Pass this offset to PHP. In PHP convert this offset into a valid timezone name with timezone_name_from_abbr function. // Just an example. $timezone_offset_minutes = -360; // $_GET['timezone_offset_minutes'] // Convert minutes to seconds $timezone_name = timezone_name_from_abbr("", $timezone_offset_minutes*60, false); // America/Chicago echo $timezone_name;</code></pre>
我写过一篇关于它的博文:如何在PHP中检测用户时区。它还包含一个演示。
所有的魔力似乎都在
visitortime.getTimezoneOffset()
真酷,我还不知道呢。它能在ie浏览器上运行吗?从这里你应该能够使用JavaScript到Ajax,设置cookie等等。我自己可能也会吃饼干。
不过,您需要允许用户更改它。我们曾尝试使用地理定位(通过maxmind)来实现这一点,但这是错误的,不值得这么做。所以我们让用户在他们的配置文件中设置它,并向还没有设置的用户显示一个通知。
在实际的HTML代码或任何用户代理字符串中没有这样的方法来计算时区,但您可以做的是使用JavaScript创建一个基本函数来获取时区。
我还不知道如何用JavaScript编码,所以我的函数可能需要时间来制作。
但是,您也可以尝试使用JavaScript在Date部分中的getTzimezoneOffset()函数或简单地使用new Date(). gettimezoneoffset();来获得实际的时区。