Friday, January 18, 2013


What happens when calling Timezone.getTimezone("blabla")?

Even seen, what happens when you access a Timezone using java.uil.Timezone.getTimezone("blabla")? I would expect an exception to be thrown, since the input is completely invalid, but nothing similar happens. The method silently returns a TimeZone initialized to GMT+0.
But there are other flaws in TimeZone. At a first look, it looks like an immutable object, but when look at it carefully, there is a setId(String) method. This allows to set the time zone ID to an arbitrary value:
TimeZone tz = Timezone.getTimezone("Europe/Zurich"); 
     // will return a zone with GMT+1 offset (DST ignored)
     // now we have a time zone 'blabla' with identical offsets.

This results in the following output:

Obviously this API is very dangerous. So looking forward what JSR 310 will bring...

JDK used was 1.7.09 and jdk-8-ea-bin-b74-windows-x64-24_jan_2013, but it is similarly also the case in earlier versions.

1 comment:

  1. Totally agree, the Timezone.getTimeZone(...) method is inherently dangerous. Falling back to GMT silently can cause lots of downstream problems. The only upside is that the method is honest about this broken behaviour in its Javadoc.

    Generally, if you have application logic that requires a timezone lookup, I tend to iterate over the TimeZone.getAvailableIds(...) and compare the id with this table - before then calling TimeZone.getTimeZone(...). If timezones are required in a tight loop, I iterate over the array once, cache the available timezones in a convenient set (or map) for faster lookup.