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

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


当前回答

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

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

节选如下:

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)

其他回答

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

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

有几种方法可以在浏览器中确定时区。如果您的浏览器提供并支持一个标准函数,那么您就应该使用它。下面是用不同格式获取相同信息的三种方法。避免使用基于特定假设或硬编码区域列表进行猜测的非标准解决方案,尽管如果没有其他办法,它们可能会有所帮助。

一旦你有了这个信息,你可以把它作为一个非标准的请求头传递给服务器,并在那里使用它。如果你还需要时区偏移量,你也可以在头文件中或请求有效载荷中传递给服务器,可以使用dateObj.getTimezoneOffset()来检索。

使用Intl API获取Olson格式(标准和推荐的方式):注意,这不是所有浏览器都支持。有关浏览器对此的支持的详细信息,请参阅此链接。 这个API可以让你获得Olson格式的时区,例如亚洲/加尔各答,美国/纽约等。

Intl . DateTimeFormat () timeZone resolvedOptions()。

使用Date对象获得较长的格式,如印度标准时间,东部标准时间等:这是所有浏览器支持的。

let dateObj =新的日期(2021,11,25,09,30,00); / /然后 dateObj.toString () / /收益率 2021年12月25日星期六09:30:00 GMT+0530(印度标准时间)//我位于印度(IST)

注意,字符串包含长格式和短格式的时区信息。你现在可以使用regex来获取这些信息:

let longZoneRegex = /\((.+)\)/; dateObj.toString () .match (longZoneRegex); / /收益率 ['(印度标准时间)','印度标准时间',索引:34,输入:' 2021年12月25日星期六09:30:00 GMT+0530(印度标准时间)',组:未定义] //注意output是一个数组,所以使用output[1]来获取时区名称。

使用Date对象获取短格式,如GMT+0530, GMT-0500等:所有浏览器都支持。

类似地,你也可以得到短格式:

let shortZoneRegex = /GMT[+-]\d{1,4}; dateObj.toString () .match (shortZoneRegex); / /收益率 ['GMT+0530',索引:25,输入:' 2021年12月25日星期六09:30:00 GMT+0530(印度标准时间)',分组:未定义] //注意output是一个数组,所以使用output[0]来获取时区名称。

下面是一篇文章(带源代码),解释如何在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).

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

JavaScript是获取客户端本地时间的最简单方法。我建议使用XMLHttpRequest发送回本地时间,如果失败,则退回到基于IP地址检测到的时区。

至于地理定位,我已经在几个项目中使用了MaxMind GeoIP,它工作得很好,尽管我不确定他们是否提供时区数据。这是一项你付费的服务,他们每月更新你的数据库。他们提供多种网络语言的包装器。