是否有一种标准的方法可以让服务器在网页中确定用户的时区?
可能来自HTTP报头或用户代理字符串的一部分?
是否有一种标准的方法可以让服务器在网页中确定用户的时区?
可能来自HTTP报头或用户代理字符串的一部分?
当前回答
下面是一个健壮的JavaScript解决方案,用于确定浏览器所在的时区。
>>> var timezone = jstz.determine();
>>> timezone.name();
"Europe/London"
https://github.com/pellepim/jstimezonedetect
其他回答
下面是一篇文章(带源代码),解释如何在ASP中确定和使用本地化时间。净(VB。NET, c#)应用程序:
是时候了
In short, the described approach relies on the JavaScript getTimezoneOffset function, which returns the value that is saved in the session cookie and used by code-behind to adjust time values between GMT and local time. The nice thing is that the user does not need to specify the time zone (the code does it automatically). There is more involved (this is why I link to the article), but provided code makes it really easy to use. I suspect that you can convert the logic to PHP and other languages (as long as you understand ASP.NET).
到目前为止,还没有报告客户端时区的HTTP标头,尽管有人建议将其包含在HTTP规范中。
如果是我,我可能会尝试使用客户端JavaScript获取时区,然后使用Ajax或其他工具将其提交给服务器。
一个简单的方法是使用:
new Date().getTimezoneOffset();
试试下面的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'];
?>
我仍然没有看到一个详细的答案在这里得到时区。你不需要按IP地址进行地理编码或使用PHP (lol)或从偏移量中错误地猜测。
首先,时区不只是与格林尼治标准时间的偏移量。这是一块由当地标准制定时间规则的土地。一些国家有夏时制,并在不同的时间开启夏令时。通常重要的是获取实际区域,而不仅仅是当前偏移量。
如果您打算存储这个时区,例如在用户首选项中,您需要的是时区,而不仅仅是偏移量。对于实时转换来说,这并不重要。
现在,要用javascript获取时区,你可以使用这个:
>> new Date().toTimeString();
"15:46:04 GMT+1200 (New Zealand Standard Time)"
//Use some regular expression to extract the time.
然而,我发现简单地使用这个健壮的插件更容易,它返回奥尔森格式的时区:
https://github.com/scottwater/jquery.detect_timezone