What is the best way to set the time zone in Tomcat for a single web app? I\'ve seen options for changing the command-line parameters or environment variables for Tomcat, but is
EDIT: I was wrong about this. This edit corrects it.
The answer is that you cannot portably set the (default) timezone for a single webapp. But if you are using Java 6 (at least), the java.util.TimeZone
class implements the default timezone methods getDefault()
, setDefault()
and setDefault(TimeZone)
using an inheritable thread local. In other words, calling setDefault()
only affects the current thread and future child threads.
The behaviour is not documented in the Sun Javadocs. It works for Java 6 and 5 (see above), but there are no guarantees it will work in older or newer Sun JREs. However, I would be very surprised if Sun decided to change/revert to a 'global' model for the default TimeZone. It would break too many existing applications, and besides globals are BAD.
With Java 7/Tomcat 7, there's a workaround/hack that allows the developer to set a unique timezone per webapp. We had to implement this in our application, as we had to support multiple webapps that run with different default timezones in the same JVM.
Other solutions that I've seen on stack overflow do not completely address the issue.
I also investigated the Java source code for TimeZone, I found a way to have a dynamic timezone returned as the default timezone for all callers by injecting a custom implementation of the JavaAWTAccess interface. This can be done by looking at the Thread class loader, and determining the actual webapp context from it, then handling that appropriately based on some webapp name to timezone mapping.
Once again, this is application server specific, and must be done differently for Tomcat, Jetty, Jboss, etc. This approach is also JVM implementation specific (only works on Oracle/Sun), but I believe can be extended to OpenJDK and others.
We have a verified working solution for Oracle JDK 7 SE + Tomcat 7, deployed on both Windows and Linux, hosting multiple webapps in different timezones.