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

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


当前回答

我认为@Matt Johnson-Pints是目前为止最好的,CanIuse搜索显示它现在被广泛采用:

.timeZone .resolvedOptions https://caniuse.com/?search=Intl.DateTimeFormat () ()

其中一个挑战是考虑为什么要知道时区。因为我认为大多数人忽略了一件事,那就是他们是可以改变的!如果一个用户带着他的笔记本电脑从欧洲旅行到美国,如果你之前把它存储在数据库中,那么他们的时区现在是不正确的(即使用户从来没有更新过他们的设备时区)。这也是@Mads Kristiansen回答的问题,因为用户会旅行——你不能把它当作给定的。

例如,我的Linux笔记本电脑关闭了“自动时区”。虽然时间可能会更新我的时区却不会。

所以我相信答案是——你需要它做什么?客户端似乎提供了一种更简单的方法来确定它,但是客户端和服务器端代码都将依赖于用户更新他们的时区或自动更新。我当然可能是错的。

其他回答

-new Date().getTimezoneOffset()/60;

getTimezoneOffset()方法将从GMT减去您的时间并返回分钟数。如果你住在GMT-8,它会返回480。

把它换算成小时,除以60。此外,请注意,符号与您需要的相反——它计算的是GMT与您的时区的偏移量,而不是您的时区与GMT的偏移量。要解决这个问题,只需乘以-1。

还要注意w3school说:

返回值不是一个常量,因为使用的惯例 日光节约时间。

这里有一种更完整的方法。

获取用户的时区偏移量 测试一些日子的夏令时边界,以确定它们是否在使用夏令时的区域。

节选如下:

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)

我认为@Matt Johnson-Pints是目前为止最好的,CanIuse搜索显示它现在被广泛采用:

.timeZone .resolvedOptions https://caniuse.com/?search=Intl.DateTimeFormat () ()

其中一个挑战是考虑为什么要知道时区。因为我认为大多数人忽略了一件事,那就是他们是可以改变的!如果一个用户带着他的笔记本电脑从欧洲旅行到美国,如果你之前把它存储在数据库中,那么他们的时区现在是不正确的(即使用户从来没有更新过他们的设备时区)。这也是@Mads Kristiansen回答的问题,因为用户会旅行——你不能把它当作给定的。

例如,我的Linux笔记本电脑关闭了“自动时区”。虽然时间可能会更新我的时区却不会。

所以我相信答案是——你需要它做什么?客户端似乎提供了一种更简单的方法来确定它,但是客户端和服务器端代码都将依赖于用户更新他们的时区或自动更新。我当然可能是错的。

一个可能的选项是使用Date报头字段,该字段在RFC 7231中定义,应该包括时区。当然,不能保证该值真的是客户机的时区,但它可以作为一个方便的起点。

使用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();
?>

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