and*_*rei 41 javascript php timezone
可能重复:
如何确定Web用户的时区?
这是最好的方法吗?php或javascript.Can有人为我提供了一些片段?谢谢.
Wes*_*y92 57
这将为您提供作为PHP变量的时区.我用jQuery和PHP编写了一个函数.经过测试,确实有效!
在您希望将时区作为变量的PHP页面上,将此代码段放在页面顶部附近:
<?php
session_start();
$timezone = $_SESSION['time'];
?>
Run Code Online (Sandbox Code Playgroud)
这将读取会话变量"time",我们现在要创建它.
在同一页面上,在本<head>节中,首先需要包含jQuery:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
Run Code Online (Sandbox Code Playgroud)
也在该<head>部分中,粘贴此jQuery:
<script type="text/javascript">
$(document).ready(function() {
if("<?php echo $timezone; ?>".length==0){
var visitortime = new Date();
var visitortimezone = "GMT " + -visitortime.getTimezoneOffset()/60;
$.ajax({
type: "GET",
url: "http://domain.com/timezone.php",
data: 'time='+ visitortimezone,
success: function(){
location.reload();
}
});
}
});
</script>
Run Code Online (Sandbox Code Playgroud)
您可能已经注意到或未注意到,但您需要将URL更改为您的实际域.
最后一件事.你可能想知道什么是timezone.php.嗯,就是这样:(创建一个名为timezone.php的新文件,并使用上面的url指向它)
<?php
session_start();
$_SESSION['time'] = $_GET['time'];
?>
Run Code Online (Sandbox Code Playgroud)
如果这样可以正常工作,它将首先加载页面,执行JavaScript并重新加载页面.然后,您将能够阅读$ timezone变量并将其用于您的乐趣!它返回当前的UTC/GMT时区偏移量(GMT -7)或您所在的任何时区.
您可以在我的博客上阅读更多相关信息
干杯
</Westy92>
小智 33
在服务器端,它将不如使用JavaScript准确.同时,有时需要解决这样的任务.在这种情况下,我只想分享可能的解决方案,我写下这个答案.
如果您需要确定用户的时区,可以通过Geo-IP服务完成.其中一些提供时区.例如,这个(http://smart-ip.net/geoip-api)可以帮助:
<?php
$ip = $_SERVER['REMOTE_ADDR']; // means we got user's IP address
$json = file_get_contents( 'http://smart-ip.net/geoip-json/' . $ip); // this one service we gonna use to obtain timezone by IP
// maybe it's good to add some checks (if/else you've got an answer and if json could be decoded, etc.)
$ipData = json_decode( $json, true);
if ($ipData['timezone']) {
$tz = new DateTimeZone( $ipData['timezone']);
$now = new DateTime( 'now', $tz); // DateTime object corellated to user's timezone
} else {
// we can't determine a timezone - do something else...
}
Run Code Online (Sandbox Code Playgroud)
Jon*_*der 11
就像Oded回答的那样.你需要在javascript中拥有这种检测功能.
我自己一直在努力,并意识到偏移是不够的.例如,它没有为您提供有关夏令时的任何信息.我最后编写了一些代码来映射到zoneinfo数据库密钥.
通过检查一年左右的几个日期,您可以更准确地确定时区.
试试这里的脚本:http://jsfiddle.net/pellepim/CsNcf/
只需更改系统时区,然后单击"运行"即可对其进行测试.如果您正在运行chrome,则需要在新选项卡中执行每个测试(并且需要重新启动safar以获取时区更改).
如果您想了解更多代码详情,请访问:https://bitbucket.org/pellepim/jstimezonedetect/