Archive for July 8, 2007

JavaScript to Get User Time Zone Information

Posted in JavaScript on July 8, 2007 by Joey

JavaScript can retrieve the time zone information of the user accessing a web page. This information is relative to Greenwich Mean Time.

var dteNow = new Date();
document.write(dteNow.getTimezoneOffset()/60);

The preceding example creates a new Date object and then executes the getTimezoneOffset method on it. getTimezoneOffset returns the difference in minutes between the user’s local time and GMT. In the example, I have divided the minutes by 60 to show the difference in hours.

After this, it’s a little tricky, because of Daylight Savings Time, to determine exactly which time zone the user is in. For example, for about half the year the offset for the Pacific Time Zone is 8. But during Daylight Savings Time, it’s 7. Depending on the needs of the program, values for the offset and the corresponding time zone can be stored in a database or XML file or some other format. The time zone offset can then be used to look up these values as needed.