Mikbe

RSS-feed

Finding time zone via JavaScript

I originally wrote this post in Norwegian. However, I found the majority of articles on this subject in my Google search seemed to give very troublesome solutions compared to mine. In hope of helping web designers also from outside Norway/Scandinavia, and as an experiment, here comes the English translation.

The idea to this came from a forum thread at Diskusjon.no, where it’s suggested using the IP in order to determine the user’s time zone. This is a very good solution, but determining country based on IP may require a bit of work and resources, as one would have to use a WHOIS-service. These cost money. The solution is also flawed for countries with more than one time zone, such as USA, Canada and Russia.

In comes my brand new JS-skills. In combination with a server side language, JS can namely be used to determine the time zone. The server’s time in GMT is given with PHP. The client determines it’s own time, compares this to the server’s, and then calculates which time zone is used on the subject computer.

  1. var currenttime = new Date();
  2. var ct = Math.floor(currenttime.getTime() / 1000);
  3. var st = '<?php echo (time() - 3600 * 1); /* set relative to GMT */?>';
  4. var ctz = Math.round((ct-st)/3600);
  5.  
  6. // ctz is now the client's timezone

Watch a demo of the script » (utilizes jQuery to change the select-attribute on the option-element)

Tagger: , , ,

2 kommentarer

  1. Kristian sier: ()

    Variabelen st skal vel ikke være en tom streng? Mangler vel litt php her…

  2. Mikael sier: ()

    Selvfølgelig. Takk! :-)

Kommenter




XHTML: Du kan bruke disse taggene: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>