Sam Su Sam Su - 6 months ago 66
Java Question

How to change Tomcat 7's server timezone?

My application deployed in a Debian vps in US, Los Angeles. So code like

new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date())
will return current time of America/Los Angeles.

Can I do some setting in Tomcat's configuration file (
server.xml
or
catalina.sh
or what?) so that get current time will return a specified TimeZone like GMT+8 or Asia/Taipei ???

Answer

With all of the different places where you can set timezones, it's (in general) always best to explicitly set the timezone when you're dealing with times. Yes, your server is in Los Angeles, but where are your users?

As explicitly dealing with timezones makes your application somewhat more complex (but also more correct, less surprising, harder to test) the next best would be to explicitly make tomcat (java) know what timezone your server clock is set to. Careful: There are some levels to set this: Set your server clock to UTC, configure your server OS to be PST and then let java know of the timezone that your server is on, e.g. in setenv.sh do CATALINA_OPTS="$CATALINA_OPTS -Duser.timezone=America/Los_Angeles" (or whatever your timezone is) to configure Java for your timezone.

Test, rinse, repeat until happy with the configuration. But make it an explicit choice on all different levels that you can set your hands on. Resolving the timezone is rather a java than a tomcat feature.

It's quite important for maintainability of your software to always store times in UTC. If you ever store in your local timezone, calculating any other timezone will be a mess - think daylight savings times, change of timezones of different areas of the world etc.

So: Set your server to UTC, then get the current time, check if it's correct. For display purposes, you might use the (user's) local timezone (e.g. PST), but for storage and calculation, UTC is highly recommended.

Comments