是否有一种标准的方法可以让服务器在网页中确定用户的时区?

可能来自HTTP报头或用户代理字符串的一部分?


当前回答

使用Unkwntech的方法,我用jQuery和PHP编写了一个函数。这是经过测试和工作!

在您希望将时区作为变量的PHP页面上,在页面顶部附近放置以下代码片段:

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

这将读取会话变量“time”,这是我们现在将要创建的。

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

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

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

您可能注意到,也可能没有注意到,但是您需要将URL更改为您实际的域。

最后一件事。你可能想知道timezone.php到底是什么。其实很简单: (创建一个名为timezone.php的新文件,并使用上面的URL指向它)

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

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

其他回答

如果您碰巧使用OpenID进行身份验证,Simple Registration Extension将解决经过身份验证的用户的问题(您需要从tz转换为numeric)。

另一种选择是根据用户代理的国家偏好推断时区。这是一种有点粗糙的方法(不适用于en-US),但可以很好地近似。

你可以在客户端使用moment-timezone将值发送给服务器;示例用法:

> moment.tz.guess()
"America/Asuncion"

使用PHP日期函数,您将获得网站所在服务器的日期时间。获取用户时间的唯一方法是使用JavaScript。

但是我建议你,如果你的网站有注册要求,那么最好的方法是要求用户注册作为一个强制性的字段。您可以在注册页面中列出各种时区,并将其保存在数据库中。在此之后,如果用户登录到站点,那么您可以根据用户选择的时区为该会话设置默认时区。

可以使用PHP函数date_default_timezone_set设置任何特定的时区。为用户设置指定的时区。

基本上,用户的时区会传到客户端,所以我们必须使用JavaScript。

下面是使用PHP和JavaScript获取用户时区的脚本。

<?php
    #http://www.php.net/manual/en/timezones.php List of Time Zones
    function showclienttime()
    {
        if(!isset($_COOKIE['GMT_bias']))
        {
?>

            <script type="text/javascript">
                var Cookies = {};
                Cookies.create = function (name, value, days) {
                    if (days) {
                        var date = new Date();
                        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                        var expires = "; expires=" + date.toGMTString();
                    }
                    else {
                        var expires = "";
                    }
                    document.cookie = name + "=" + value + expires + "; path=/";
                    this[name] = value;
                }

                var now = new Date();
                Cookies.create("GMT_bias",now.getTimezoneOffset(),1);
                window.location = "<?php echo $_SERVER['PHP_SELF'];?>";
            </script>

            <?php

        }
        else {
          $fct_clientbias = $_COOKIE['GMT_bias'];
        }

        $fct_servertimedata = gettimeofday();
        $fct_servertime = $fct_servertimedata['sec'];
        $fct_serverbias = $fct_servertimedata['minuteswest'];
        $fct_totalbias = $fct_serverbias – $fct_clientbias;
        $fct_totalbias = $fct_totalbias * 60;
        $fct_clienttimestamp = $fct_servertime + $fct_totalbias;
        $fct_time = time();
        $fct_year = strftime("%Y", $fct_clienttimestamp);
        $fct_month = strftime("%B", $fct_clienttimestamp);
        $fct_day = strftime("%d", $fct_clienttimestamp);
        $fct_hour = strftime("%I", $fct_clienttimestamp);
        $fct_minute = strftime("%M", $fct_clienttimestamp);
        $fct_second = strftime("%S", $fct_clienttimestamp);
        $fct_am_pm = strftime("%p", $fct_clienttimestamp);
        echo $fct_day.", ".$fct_month." ".$fct_year." ( ".$fct_hour.":".$fct_minute.":".$fct_second." ".$fct_am_pm." )";
    }

    showclienttime();
?>

但在我看来,最好是询问用户在你的项目中是否必须注册。

首先,了解JavaScript中的时区检测是不完善的。您可以在date对象的实例上使用getTimezoneOffset获取特定日期和时间的本地时区偏移量,但这与完整的IANA时区(如America/Los_Angeles)不完全相同。

以下是一些可行的方法:

大多数现代浏览器在实现ECMAScript国际化API时都支持IANA时区,所以你可以这样做:

const tzid = Intl.DateTimeFormat().solveOptions().timeZone; console.log(tzid);

结果是一个字符串,其中包含运行代码的计算机的IANA时区设置。

支持的环境列在Intl兼容性表中。展开DateTimeFormat部分,并查看名为resolvedOptions()的特性。timeZone默认为主机环境。

Some libraries, such as Luxon use this API to determine the time zone through functions like luxon.Settings.defaultZoneName. If you need to support an wider set of environments, such as older web browsers, you can use a library to make an educated guess at the time zone. They work by first trying the Intl API if it's available, and when it's not available, they interrogate the getTimezoneOffset function of the Date object, for several different points in time, using the results to choose an appropriate time zone from an internal data set. Both jsTimezoneDetect and moment-timezone have this functionality. // using jsTimeZoneDetect var tzid = jstz.determine().name(); // using moment-timezone var tzid = moment.tz.guess(); In both cases, the result can only be thought of as a guess. The guess may be correct in many cases, but not all of them. Additionally, these libraries have to be periodically updated to counteract the fact that many older JavaScript implementations are only aware of the current daylight saving time rule for their local time zone. More details on that here.

最终,更好的方法是向用户询问他们所在的时区。提供一个他们可以改变的设置。你可以使用上面的选项之一来选择一个默认设置,但不要让它不可能偏离你的应用程序。

还有一种完全不同的方法,即完全不依赖用户电脑的时区设置。相反,如果可以收集纬度和经度坐标,则可以使用以下方法之一将它们解析为时区。这在移动设备上效果很好。

我仍然没有看到一个详细的答案在这里得到时区。你不需要按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