Monday, March 23, 2009

Determine the Java TimeZone of your web visitors using client-side javascript

You want your Java web application to know what TimeZone your visitors are in. You can use client-side javascript code like the following to produce a timezone string that Java can understand:
function getTimezone() {
  var tzo = new Date().getTimezoneOffset();  //returns timezone offset in minutes
  function pad(num, digits) {
    num = String(num); while (num.length < digits) { num="0"+num; }; return num;
  }
  return "GMT" + (tzo > 0 ? "-" : "+") + pad(Math.floor(tzo/60), 2) + ":" + pad(tzo%60, 2);
}
This will produce strings like GMT-04:00 and GMT-07:00 which you can then pass up to the server and into TimeZone.getTimeZone() to produce a TimeZone object.

3 comments:

Anonymous said...

thanks, was helpful

Unknown said...

for +04:00 etc with +
you should put something like num=abs(num)

Anonymous said...


// fixes the mentioned bug ("GMT+-2:00") with positive timezones: "GMT+02:00".

function getTimezone() {
var tzo = new Date().getTimezoneOffset(); //returns timezone offset in minutes
function pad(num, digits) {
num = String(num); while (num.length < digits) { num="0"+num; }; return num;
}
return "GMT" + (tzo > 0 ? "-" : "+") + pad(Math.floor(Math.abs(tzo)/60), 2) + ":" + pad(Math.abs(tzo)%60, 2);
}