get user timezone

121,119

Solution 1

This will get you the timezone as a PHP variable. I wrote a function using jQuery and PHP. This is tested, and does work!

On the PHP page where you are 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> section, first of all you need to include jQuery:

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

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

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

You can read more about this on my blog

Solution 2

On server-side it will be not as accurate as with JavaScript. Meanwhile, sometimes it is required to solve such task. Just to share the possible solution in this case I write this answer.

If you need to determine user's time zone it could be done via Geo-IP services. Some of them providing timezone. For example, this one (http://smart-ip.net/geoip-api) could help:

<?php
$ip     = $_SERVER['REMOTE_ADDR']; // means we got user's IP address 
$json   = file_get_contents( 'http://smart-ip.net/geoip-json/' . $ip); // this one service we gonna use to obtain timezone by IP
// maybe it's good to add some checks (if/else you've got an answer and if json could be decoded, etc.)
$ipData = json_decode( $json, true);

if ($ipData['timezone']) {
    $tz = new DateTimeZone( $ipData['timezone']);
    $now = new DateTime( 'now', $tz); // DateTime object corellated to user's timezone
} else {
   // we can't determine a timezone - do something else...
}

Solution 3

Just as Oded has answered. You need to have this sort of detection functionality in javascript.

I've struggled with this myself and realized that the offset is not enough. It does not give you any information about daylight saving for example. I ended up writing some code to map to zoneinfo database keys.

By checking several dates around a year you can more accurately determine a timezone.

Try the script here: http://jsfiddle.net/pellepim/CsNcf/

Simply change your system timezone and click run to test it. If you are running chrome you need to do each test in a new tab though (and safar needs to be restarted to pick up timezone changes).

If you want more details of the code check out: https://bitbucket.org/pellepim/jstimezonedetect/

Share:
121,119
andrei
Author by

andrei

By day: I write code By night: I write code

Updated on July 09, 2022

Comments

  • andrei
    andrei almost 2 years

    Possible Duplicate:
    How can I determine a web user's time zone?

    Which is the best way to do this ? php or javascript.Can someone provide me with some snippets ? thanks.

  • arboles
    arboles about 12 years
    i am getting an error saying $timezone undefined. why?
  • Vladas Diržys
    Vladas Diržys over 11 years
    I think this solution is fundamentally wrong (at least in some situations), because it allows the user to change the time, to whatever he wants, by simply just calling domain.com/timezone.php
  • Nathan
    Nathan over 11 years
    Will this work for timezones such as GMT +1?
  • Westy92
    Westy92 over 11 years
    It should! Give it a try and let me know if it doesn't.
  • Brilliand
    Brilliand over 10 years
    @VladasDiržys This is information provided by the user's browser. Trying to secure it against the user is pointless.
  • Matt Johnson-Pint
    Matt Johnson-Pint almost 10 years
    This only returns the current time zone offset - not the time zone. See the timezone tag wiki.
  • Matt Johnson-Pint
    Matt Johnson-Pint almost 10 years
    This is probably the most reasonable approach.
  • Smokey
    Smokey almost 10 years
    smart-ip.net is not accessible now. So this solution is vague. I think they shutdown their server. So use this code at your own risk because the result returned by this is null.
  • Chinmay235
    Chinmay235 over 9 years
    (-1) smart-ip.net/geoip-json/202.191.214.178 - Service Temporary Unavailable
  • Rodrigo Kravetz
    Rodrigo Kravetz almost 9 years
    For positive GMT it returns without the + symbol: for example GMT 3, instead of GMT +3.
  • ltvie
    ltvie almost 9 years
    thanks, this what i was looking for !
  • JasonH
    JasonH over 8 years
    99% of the time this works. Once in a while my browser will get stuck in infinite redirects as the timezone offset never gets set. anyone else experience this?
  • Keith Holliday
    Keith Holliday about 8 years
    You can try this site now: ip-api.com/json .
  • Luke
    Luke almost 8 years
    I did with same result as before
  • Christopher K.
    Christopher K. over 6 years
    Be careful when using $timezone - an attacker can set it to anything. If you use it in an SQL query like "SELECT * FROM places WHERE timezone=$timezone" then you will have an SQL Injection. If you echo it in your HTML like echo "Your Timezone: $timezone", you will have an XSS. This is user input, treat it as such.
  • ed22
    ed22 about 4 years
    Also, won't help if you want to render dates on server based on client's time zone. The source has been delivered and it's too late ;)