Sunday, August 31, 2008

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

1 comment:

Anonymous said...

Interesting post as for me. I'd like to read something more about that matter. Thank you for posting this material.
Joan Stepsen
Tech and gadgets


Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 2.5 License.