Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/89.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Html 确定用户';s时区_Html_Browser_Timezone_User Agent_Timezone Offset - Fatal编程技术网

Html 确定用户';s时区

Html 确定用户';s时区,html,browser,timezone,user-agent,timezone-offset,Html,Browser,Timezone,User Agent,Timezone Offset,web服务器是否有一种标准方法可以确定网页中用户的时区 可能来自HTTP头或用户代理字符串的一部分?到目前为止,没有报告客户端时区的HTTP头,尽管建议将其包括在HTTP规范中 如果是我,我可能会尝试使用客户端JavaScript获取时区,然后使用Ajax或其他方式将其提交给服务器。JavaScript是获取客户端本地时间的最简单方法。我建议使用一个发送回本地时间,如果失败,则返回基于其IP地址检测到的时区 至于地理定位,我已经在几个项目中使用过,而且效果很好,尽管我不确定它们是否提供时区数据。

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


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

到目前为止,没有报告客户端时区的HTTP头,尽管建议将其包括在HTTP规范中


如果是我,我可能会尝试使用客户端JavaScript获取时区,然后使用Ajax或其他方式将其提交给服务器。

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

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

我所见过的确定时区的最流行(=标准?)方法就是简单地询问用户自己。如果您的网站需要订阅,可以将其保存在用户的配置文件数据中。对于anon用户,日期可以显示为UTC或GMT或类似的格式


我不是想成为一个聪明人。只是有时候有些问题在任何编程环境之外都有更好的解决方案。

所有的魔力似乎都在其中

visitortime.getTimezoneOffset()
那很酷,我不知道。它在Internet Explorer等中工作吗?从那以后,您应该能够使用JavaScript到Ajax,设置cookies等等。我可能会自己去吃饼干

不过,您需要允许用户更改它。不久前,我们尝试使用地理定位(via
maxmind
)来实现这一点,但这是错误的,不值得这么做。因此,我们只需让用户在其配置文件中进行设置,并向尚未设置的用户显示一条通知。

如果您碰巧使用进行身份验证,将解决已验证用户的问题(您需要将tz转换为数字)

另一种选择是根据用户代理的国家/地区偏好推断时区。这是一个有点粗糙的方法(对en-US不起作用),但它是一个很好的近似值

-new Date().getTimezoneOffset()/60;
方法
getTimezoneOffset()
将从GMT中减去您的时间并返回分钟数。所以,如果你住在GMT-8,它将返回480

若要将其转换为小时数,请除以60。另外,请注意,该符号与您需要的符号相反-它计算的是GMT与您所在时区的偏移量,而不是您所在时区与GMT的偏移量。要解决此问题,只需将其乘以-1即可

还要注意的是:

由于使用 夏时制

下面是一篇文章(含源代码),解释如何在ASP.NET(VB.NET,C#)应用程序中确定和使用本地化时间:


简而言之,所描述的方法依赖于JavaScript
getTimezoneOffset
函数,该函数返回保存在会话cookie中的值,代码隐藏使用该值来调整GMT和本地时间之间的时间值。好在用户不需要指定时区(代码会自动指定)。其中涉及的内容更多(这就是我链接到本文的原因),但提供的代码使其真正易于使用。我怀疑您可以将逻辑转换为PHP和其他语言(只要您理解ASP.NET)

使用PHP
date
功能,您将获得站点所在服务器的日期和时间。获得用户时间的唯一方法是使用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();
?>
但是我建议你,如果你的网站需要注册,那么最好的方法就是在注册时要求用户注册。您可以在注册页面中列出各种时区,并将其保存在数据库中。在此之后,如果用户登录到站点,则可以根据用户选择的时区设置该会话的默认时区

您可以使用PHP函数
date\u default\u timezone\u 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();
?>

var Cookies={};
Cookies.create=函数(名称、值、天数){
如果(天){
变量日期=新日期();
date.setTime(date.getTime()+(天*24*60*60*1000));
var expires=“;expires=“+date.togmString();
}
否则{
var=”;
}
document.cookie=name+“=”+value+expires+“path=/”;
此[名称]=值;
}
var now=新日期();
create(“GMT_bias”,now.getTimezoneOffset(),1);
window.location=“”;

但根据我的观点,最好询问用户在项目中是否强制注册。

这里有一个更完整的方法

  • 获取用户的时区偏移量
  • 在夏令时边界上测试几天,以确定它们是否位于使用夏令时的区域中
  • 摘录如下:

    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;
    }
    
    函数TimezoneDetect(){
    var dtDate=new Date('1/1/'+(new Date()).getUTCFullYear());
    var intOffset=10000;//将初始偏移设置为高,以便在第一次尝试时对其进行调整
    每月的风险值;
    var intHoursUtc;
    var整数小时;
    var intDaysMultiplyBy;
    //检查每个月,找出DST的最低偏移量
    对于(intMonth=0;intMonth<12;intMonth++){
    //去下个月
    dtDate.setUTCMonth(dtDate.getUTCMonth()+1);
    
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
    
    <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>
    
    <?php
        session_start();
        $_SESSION['time'] = $_GET['time'];
    ?>
    
    function maketimus(timestampz)
    {
        var linktime = new Date(timestampz * 1000);
        var linkday = linktime.getDate();
        var freakingmonths = new Array();
    
        freakingmonths[0]  = "jan";
        freakingmonths[1]  = "feb";
        freakingmonths[2]  = "mar";
        freakingmonths[3]  = "apr";
        freakingmonths[4]  = "may";
        freakingmonths[5]  = "jun";
        freakingmonths[6]  = "jul";
        freakingmonths[7]  = "aug";
        freakingmonths[8]  = "sep";
        freakingmonths[9]  = "oct";
        freakingmonths[10] = "nov";
        freakingmonths[11] = "dec";
    
        var linkmonthnum = linktime.getMonth();
        var linkmonth = freakingmonths[linkmonthnum];
        var linkyear = linktime.getFullYear();
        var linkhour = linktime.getHours();
        var linkminute = linktime.getMinutes();
    
        if (linkminute < 10)
        {
            linkminute = "0" + linkminute;
        }
    
        var fomratedtime = linkday + linkmonth + linkyear + " " +
                           linkhour + ":" + linkminute + "h";
        return fomratedtime;
    }
    
    echo '<script type="text/javascript">
    var eltimio = maketimus('.$unix_timestamp_ofshiz.');
    document.write(eltimio);
    </script><noscript>pls enable javascript</noscript>';
    
    new Date().getTimezoneOffset();
    
    <?php
    session_start();
    
    if(!isset($_SESSION['timezone']))
    {
        if(!isset($_REQUEST['offset']))
        {
        ?>
            <script>
            var d = new Date()
            var offset= -d.getTimezoneOffset()/60;
            location.href = "<?php echo $_SERVER['PHP_SELF']; ?>?offset="+offset;
            </script>
            <?php   
        }
        else
        {
            $zonelist = array('Kwajalein' => -12.00, 'Pacific/Midway' => -11.00, 'Pacific/Honolulu' => -10.00, 'America/Anchorage' => -9.00, 'America/Los_Angeles' => -8.00, 'America/Denver' => -7.00, 'America/Tegucigalpa' => -6.00, 'America/New_York' => -5.00, 'America/Caracas' => -4.30, 'America/Halifax' => -4.00, 'America/St_Johns' => -3.30, 'America/Argentina/Buenos_Aires' => -3.00, 'America/Sao_Paulo' => -3.00, 'Atlantic/South_Georgia' => -2.00, 'Atlantic/Azores' => -1.00, 'Europe/Dublin' => 0, 'Europe/Belgrade' => 1.00, 'Europe/Minsk' => 2.00, 'Asia/Kuwait' => 3.00, 'Asia/Tehran' => 3.30, 'Asia/Muscat' => 4.00, 'Asia/Yekaterinburg' => 5.00, 'Asia/Kolkata' => 5.30, 'Asia/Katmandu' => 5.45, 'Asia/Dhaka' => 6.00, 'Asia/Rangoon' => 6.30, 'Asia/Krasnoyarsk' => 7.00, 'Asia/Brunei' => 8.00, 'Asia/Seoul' => 9.00, 'Australia/Darwin' => 9.30, 'Australia/Canberra' => 10.00, 'Asia/Magadan' => 11.00, 'Pacific/Fiji' => 12.00, 'Pacific/Tongatapu' => 13.00);
            $index = array_keys($zonelist, $_REQUEST['offset']);
            $_SESSION['timezone'] = $index[0];
        }
    }
    
    date_default_timezone_set($_SESSION['timezone']);
    
    //rest of your code goes here
    ?>
    
    -new Date().getTimezoneOffset()/60;
    
    <?php
        $ip = $_SERVER['REMOTE_ADDR'];
        $json = file_get_contents("http://api.easyjquery.com/ips/?ip=" . $ip . "&full=true");
        $json = json_decode($json,true);
        $timezone = $json['LocalTimeZone'];
    ?>
    
    >>> var timezone = jstz.determine();
    >>> timezone.name(); 
    "Europe/London"
    
    >> new Date().toTimeString();
    "15:46:04 GMT+1200 (New Zealand Standard Time)"
    //Use some regular expression to extract the time.
    
    $.ajaxSetup({
        beforeSend: function(xhr, settings) {
            xhr.setRequestHeader("X-TZ-Offset", -new Date().getTimezoneOffset()/60);
        }
    });
    
    var off = (-new Date().getTimezoneOffset()/60).toString();//note the '-' in front which makes it return positive for negative offsets and negative for positive offsets
    var tzo = off == '0' ? 'GMT' : off.indexOf('-') > -1 ? 'GMT'+off : 'GMT+'+off;
    
    $ts = new DateTime('now', new DateTimeZone($_POST['tzo']);
    $user_time = $ts->format("F j, Y, g:i a");//will return the users current time in readable format, regardless of whether date_default_timezone() is set or not.
    $user_timestamp = strtotime($user_time);
    
    $date_created = // Get from the database
    $created = date("F j, Y, g:i a",$date_created); // Return it to the user or whatever
    
    > moment.tz.guess()
    "America/Asuncion"
    
    var timezone_offset_minutes = new Date().getTimezoneOffset();
    timezone_offset_minutes = timezone_offset_minutes == 0 ? 0 : -timezone_offset_minutes;
    
    // Just an example.
    $timezone_offset_minutes = -360;  // $_GET['timezone_offset_minutes']
    
    // Convert minutes to seconds
    $timezone_name = timezone_name_from_abbr("", $timezone_offset_minutes*60, false);
    
    // America/Chicago
    echo $timezone_name;</code></pre>