Get your clients timezone using JavaScript

Created by
Tuesday, July 12, 2016

Developing and application that can know what TimeZone your visitors are in as the visit your site. Using client-side javascript code like the following to produce a timezone string that Java can understand:

function getTimezone() {
  var timezone = new Date().getTimezoneOffset();  

  function pad(num, digits) {
    num = String(num); while (num.length < digits) { num="0"+num; }; return num;
  }
  
  return "GMT" + (timezone > 0 ? "-" : "+") + pad(Math.floor(timezone/60), 2) + ":" + pad(timezone%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.

6
Rating
1 2 3 4 5

Save

Saved

Report

Reported
Reasons
Cancel
0 comments