Developer tips

Time Zones and Java Web Applications

The TimeZone (as well as the locale and encoding) are retrieved by the JVM from the operating system. This in my opinion is not a good decision, but that’s not the point – it’s as it is.

So how do we set the time zone of a Java web application? There are a number of ways:

change the operating system default

pass the following option on the command line: -Duser.timezone=Europe/Helsinki

set it using TimeZone.setDefault(TimeZone.getTimeZone("Europe/Helsinki"). This should be done in a ServletContextListener that is defined before all other listeners in web.xml

What if you need multiple timezones to be supported on your site? Then you have to pass the timezone for the current user to each control/tag that displays dates. It is explained here how to do this with javascript, but I’d recommend on simply asking the user what’s his timezone (if possible)

Note: if you are using joda-time, then use DateTimeZone.setDefault(..)