Monday, April 13, 2009

How to get the server's timezone

The problem
How to get the server's timezone display name correctly and display it to the user in his locale.

server's default timezone
Firstly, you need to get the server's default timezone. This is easily achieved by the following call

final TimeZone timeZone = TimeZone.getDefault();
use daylight time?
Secondly, you need to find out if this timezone uses daylight time. This is important as some timezones change their names during daylight saving. Don't use the TimeZone.useDaylightTime() method

//final boolean daylight = timeZone.useDaylightTime();
This method works fine only for systems where the timezone never changes. If the administrator changes the time on the server, this change won't be reflected in subsequent calls. What you need to do instead, is to find out is the daylight savings is on right now.

final boolean daylight = timeZone.inDaylightTime(new Date());
user's locale
The last important step is to get the right locale, the locale you want this timezone name to display in. You could call Locale.getDefault(), but this returns server's default locale. You want the locale that the user is using. In a web application, the user's locale can be obtained from getLocale() method of ServletRequest object.

final Locale locale = servletRequest.getLocale();
final step - timezone display name
Now we can call getDisplayName method with all required parameters.

return timeZone.getDisplayName(daylight, TimeZone.LONG, locale);
Solution
To put this all together, the final solution may look like this method

private String getServerTimeZoneDisplayName(){ final TimeZone timeZone = TimeZone.getDefault(); final boolean daylight = timeZone.inDaylightTime(new Date()); final Locale locale = servletRequest.getLocale(); return timeZone.getDisplayName(daylight, TimeZone.LONG, locale);}

References

Java TimeZone class
JEE ServletRequest class
JRA-15488 - Shows incorrect time (zone) when subscribing to filter

No comments: