Determine a user's timezone

前端 未结 25 2934
刺人心
刺人心 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:28

    I still have not seen a detailed answer here that gets the time zone. You shouldn't need to geocode by IP address or use PHP (lol) or incorrectly guess from an offset.

    Firstly a time zone is not just an offset from GMT. It is an area of land in which the time rules are set by local standards. Some countries have daylight savings, and will switch on DST at differing times. It's usually important to get the actual zone, not just the current offset.

    If you intend to store this timezone, for instance in user preferences you want the zone and not just the offset. For realtime conversions it won't matter much.

    Now, to get the time zone with javascript you can use this:

    >> new Date().toTimeString();
    "15:46:04 GMT+1200 (New Zealand Standard Time)"
    //Use some regular expression to extract the time.
    

    However I found it easier to simply use this robust plugin which returns the Olsen formatted timezone:

    https://github.com/scottwater/jquery.detect_timezone

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

    All the magic seems to be in

    visitortime.getTimezoneOffset()
    

    That's cool, I didn't know about that. Does it work in Internet Explorer etc? From there you should be able to use JavaScript to Ajax, set cookies whatever. I'd probably go the cookie route myself.

    You'll need to allow the user to change it though. We tried to use geo-location (via maxmind) to do this a while ago, and it was wrong enough to make it not worth doing. So we just let the user set it in their profile, and show a notice to users who haven't set theirs yet.

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

    Getting a valid TZ Database timezone name in PHP is a two-step process:

    1. With JavaScript, get timezone offset in minutes through getTimezoneOffset. This offset will be positive if the local timezone is behind UTC and negative if it is ahead. So you must add an opposite sign to the offset.

      var timezone_offset_minutes = new Date().getTimezoneOffset();
      timezone_offset_minutes = timezone_offset_minutes == 0 ? 0 : -timezone_offset_minutes;
      

      Pass this offset to PHP.

    2. In PHP convert this offset into a valid timezone name with timezone_name_from_abbr function.

      // 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>
      

    I've written a blog post on it: How to Detect User Timezone in PHP. It also contains a demo.

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

    One possible option is to use the Date header field, which is defined in RFC 7231 and is supposed to include the timezone. Of course, it is not guaranteed that the value is really the client's timezone, but it can be a convenient starting point.

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

    Easy, just use the JavaScript getTimezoneOffset function like so:

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

    Using Unkwntech's approach, I wrote a function using jQuery and PHP. This is tested and does work!

    On the PHP page where you want to have the timezone as a variable, have this snippet of code somewhere near the top of the page:

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

    This will read the session variable "time", which we are now about to create.

    On the same page, in the <head>, you need to first of all include jQuery:

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

    Also in the <head>, below the jQuery, paste this:

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

    You may or may not have noticed, but you need to change the URL to your actual domain.

    One last thing. You are probably wondering what the heck timezone.php is. Well, it is simply this: (create a new file called timezone.php and point to it with the above URL)

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

    If this works correctly, it will first load the page, execute the JavaScript, and reload the page. You will then be able to read the $timezone variable and use it to your pleasure! It returns the current UTC/GMT time zone offset (GMT -7) or whatever timezone you are in.

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