获取用户时区

2022-08-30 11:48:13

可能的重复:
如何确定网络用户的时区?

这是最好的方法吗?php 或 javascript。有人可以给我一些片段吗?谢谢。


答案 1

这将为您提供时区作为PHP变量。我使用jQuery和PHP编写了一个函数。这是经过测试的,并且确实有效!

在您希望将时区作为变量的 PHP 页面上,将此代码段放在页面顶部附近的某个位置:

<?php    
    session_start();
    $timezone = $_SESSION['time'];
?>

这将读取会话变量“time”,我们现在即将创建该变量。

在同一页面上,在本节中,首先您需要包含jQuery:<head>

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>

同样在本节中,粘贴以下jQuery:<head>

<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://example.com/timezone.php",
                data: 'time='+ visitortimezone,
                success: function(){
                    location.reload();
                }
            });
        }
    });
</script>

您可能已经注意到了,也可能没有注意到,但是您需要将网址更改为您的实际域。

最后一件事。您可能想知道.php是什么。好吧,它只是这样:(创建一个名为时区的新文件.php并使用上面的url指向它)

<?php
    session_start();
    $_SESSION['time'] = $_GET['time'];
?>

如果这工作正常,它将首先加载页面,执行 JavaScript,然后重新加载页面。然后,您将能够阅读$timezone变量,并将其用于您的乐趣!它返回当前 UTC/GMT 时区偏移量 (GMT -7) 或您所在的任何时区。

您可以在我的博客上阅读更多相关信息


答案 2

在服务器端,它不会像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...
}