Determine a user's timezone

前端 未结 25 2876
刺人心
刺人心 2020-11-21 07:12

Is there a standard way for a web server to be able to determine a user\'s timezone within a web page?

Perhaps from an HTTP header or part of the user-agent

相关标签:
25条回答
  • 2020-11-21 07:18

    With the PHP date function you will get the date time of server on which the site is located. The only way to get the user time is to use JavaScript.

    But I suggest you to, if your site has registration required then the best way is to ask the user while to have registration as a compulsory field. You can list various time zones in the register page and save that in the database. After this, if the user logs in to the site then you can set the default time zone for that session as per the users’ selected time zone.

    You can set any specific time zone using the PHP function date_default_timezone_set. This sets the specified time zone for users.

    Basically the users’ time zone is goes to the client side, so we must use JavaScript for this.

    Below is the script to get users’ time zone using PHP and 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();
    ?>
    

    But as per my point of view, it’s better to ask to the users if registration is mandatory in your project.

    0 讨论(0)
  • 2020-11-21 07:19

    Here is an article (with source code) that explains how to determine and use localized time in an ASP.NET (VB.NET, C#) application:

    It's About Time

    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).

    0 讨论(0)
  • 2020-11-21 07:20

    The most popular (==standard?) way of determining the time zone I've seen around is simply asking the users themselves. If your website requires subscription, this could be saved in the users' profile data. For anon users, the dates could be displayed as UTC or GMT or some such.

    I'm not trying to be a smart aleck. It's just that sometimes some problems have finer solutions outside of any programming context.

    0 讨论(0)
  • 2020-11-21 07:20

    You could do it on the client with moment-timezone and send the value to server; sample usage:

    > moment.tz.guess()
    "America/Asuncion"
    
    0 讨论(0)
  • 2020-11-21 07:21

    A simple way to do it is by using:

    new Date().getTimezoneOffset();
    
    0 讨论(0)
  • 2020-11-21 07:22

    Here is a more complete way.

    1. Get the timezone offset for the user
    2. Test some days on daylight saving boundaries to determine if they are in a zone that uses daylight saving.

    An excerpt is below:

    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;
    }
    

    Getting TZ and DST from JS (via Way Back Machine)

    0 讨论(0)
提交回复
热议问题