How to get the timezone offset with JavascriptHow to get the timezone offset with Javascript

Posted February 17th, 2009 in Javascript

There may be times when you want to work out what the difference in timezone is between the web browser client and the web server. This is possible using the Javascript Date object's getTimezoneOffset() function.

Example usage:

<script language="Javascript">

var dt = new Date();
window.alert(dt.getTimezoneOffset());

// OR

window.alert(new Date().getTimezoneOffset());

</script>

The time zone offset returned

The value returned from getTimezoneOffset() is the number of minutes different from GMT/UTC time. To get the number of hours you need to divide the number returned by 60, noting that there are some timezones in the world that are not even 1 hour intervals (e.g. the Chatham Islands which is UTC +13:45 and New Delhi which is UTC +5:30).

One thing I have noticed is the number returned is the negative of what is expected. For example, I am in New Zealand and the expected offset at the moment is +13 (it's currently daylight savings time here) because we are 13 hours ahead of UTC. However, the getTimezoneOffset() function returns -13 so this is something to watch out for.

Modifying the above example to get the timezone in hours:

<script language="Javascript">

window.alert(new Date().getTimezoneOffset() / 60);

</script>

Related posts:

Comments

blog comments powered by Disqus