43

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.

Community
  • 1
  • 1
andrei
  • 8,252
  • 14
  • 51
  • 66

3 Answers3

60

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

Westy92
  • 19,087
  • 4
  • 72
  • 54
  • 1
    i am getting an error saying $timezone undefined. why? – arboles May 13 '12 at 06:09
  • 7
    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 http://domain.com/timezone.php – Vladas Diržys Sep 21 '12 at 11:13
  • Will this work for timezones such as `GMT +1`? – Nathan Feb 16 '13 at 04:11
  • It should! Give it a try and let me know if it doesn't. – Westy92 Feb 18 '13 at 03:09
  • 13
    @VladasDiržys This is information provided by the user's browser. Trying to secure it against the user is pointless. – Brilliand Feb 13 '14 at 17:19
  • 3
    This only returns the *current* time zone offset - not the *time zone*. See [the timezone tag wiki](http://stackoverflow.com/tags/timezone/info). – Matt Johnson-Pint Jul 12 '14 at 22:56
  • For positive GMT it returns without the + symbol: for example GMT 3, instead of GMT +3. – Rodrigo Kravetz Jul 12 '15 at 10:08
  • thanks, this what i was looking for ! – ltvie Aug 01 '15 at 01:33
  • 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? – JasonH Sep 30 '15 at 02:01
  • 1
    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. – Christopher K. Sep 22 '17 at 08:58
  • 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 ;) – ed22 Mar 10 '20 at 22:38
36

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...
}
Mikhus
  • 1,069
  • 11
  • 8
14

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/

Jon Nylander
  • 8,743
  • 5
  • 34
  • 45