Get a User's Timezone using JavaScript/jQuery and PHP


I wrote a function using jQuery and PHP that I have tested.

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:

   $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="">

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

<script type="text/javascript">
   $(function() {
      if (0 == "<?=$timezone?>".length) {
         var visitortime = new Date();
         var visitortimezone = "GMT " + -visitortime.getTimezoneOffset() / 60;
            type: "GET",
            url: "", // Change this!
            data: 'time='+ visitortimezone,
            success: function(){

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)

   $_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.

comments powered by Disqus