Friday, January 18, 2013

java.util.Timezone

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)
tz.setId("blabla");
     // now we have a time zone 'blabla' with identical offsets.
System.out.println(tz);

This results in the following output:
sun.util.calendar.ZoneInfo[id="blabla",offset=3600000,dstSavings=3600000,useDaylight=true,transitions=119,lastRule=java.util.SimpleTimeZone[id=blabla,offset=3600000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=2,startMonth=2,startDay=-1,startDayOfWeek=1,startTime=3600000,startTimeMode=2,endMode=2,endMonth=9,endDay=-1,endDayOfWeek=1,endTime=3600000,endTimeMode=2]]

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.

    ReplyDelete