java.util.TimeZone is Broken by Design

Look at this stupid code:


/**
 * Gets the TimeZone for the given ID.
 *
 * @param ID the ID for a TimeZone, either an abbreviation
 * such as "PST", a full name such as "America/Los_Angeles", 
 * or a custom
 * ID such as "GMT-8:00". Note that the support of 
 * abbreviations is
 * for JDK 1.1.x compatibility only and full names should be used.
 *
 * @return the specified TimeZone, or the GMT zone if the given ID
 * cannot be understood.
 */
public static synchronized TimeZone getTimeZone(String ID) {
    return getTimeZone(ID, true);
}

private static TimeZone getTimeZone( String ID, 
                                     boolean fallback) {
    TimeZone tz = ZoneInfo.getTimeZone(ID);

    if (tz == null) {
	        tz = parseCustomTimeZone(ID);
	        if (tz == null && fallback) {
		        tz = new ZoneInfo(GMT_ID, 0);
	        }
	    }
    
    return tz;

}

… so we have a getTimeZone method and I can pass it a string. OK. What if I pass it in an invalid string like ‘asdfasdfaeeafaljaljdflj’.

Well then the getTimeZone method goes into fallback mode and uses GMT (zone zero).

That might be reasonable but I’d like to disable fallback fallback and have it return null.

Nope. Can’t do that because the overloaded getTimeZone method is private.

We can’t even test if this exception is raised because UTC/GMT is a perfectly valid time zone.

This is with the latest JDK 1.6 sources so this bug has existed at least since JDK 1.4 which is more than 5 years old.

This is why Java needed to be Open Source 10 years ago.


  1. Ismael Juma

    That is just one of many reasons why we need JSR-310[1] yesterday. ;)

    Ismael

    [1] https://jsr-310.dev.java.net/

  2. It should have RFC 822 and ISO 8601 parsers as well.

    I finally broke down and had to write my own …

    Kevin

  3. DAR

    So … don’t just complain about it. File a bug requesting to make that method public. I’d expect that the only reason this has existed since 1.4 is that nobody made any effort to try to get it fixed.

    Java may not have been open source for all it’s life. But IMO Sun has generally been good at taking community feedback with Java, including fixing bugs. I’ve filed numerous Java bugs over the years, and had them fixed in pretty short order.






%d bloggers like this: