Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't TimeZone.getTimeZone() throw an exception

Tags:

java

timezone

Why doesn't TimeZone.getTimeZone() method throw an error if it is given an invalid time zone ID? Instead it returns "the GMT zone if the given ID cannot be understood". What's the rationale behind this decision?

like image 235
armandino Avatar asked Oct 17 '25 02:10

armandino


2 Answers

I'm not sure of the rationale, but they did provide you with a getAvailableIDs() method to allow you to ensure your timezone is vaild. They do mention this in the javadoc:

You can use the getAvailableIDs method to iterate through all the supported time zone IDs. You can then choose a supported ID to get a TimeZone. If the time zone you want is not represented by one of the supported IDs, then a custom time zone ID can be specified to produce a TimeZone

like image 144
Lucas Avatar answered Oct 18 '25 16:10

Lucas


One cause of this and similar woes of Java (that one must take special care to avoid dependence on the system's default locale, charset and timezone, to get exceptions when character conversion fails when reading a text file or writing a text file fails because the disk is full etc.) may be that Java was first applied for programming user interfaces, not server backends: in a UI, it may be better to display erroneous output than fail completely, as the user can often figure out the error and interpret the existing output correctly. Nevertheless, I think that the omission of exceptions in TimeZone.getTimeZone(String) was a design mistake.

Anyway, there is new and better API available now. The modern way to get a time zone (starting from Java 8) is

TimeZone.getTimeZone(ZoneId.of(zoneId));

which does throw an exception for an invalid zone ID. The zone ID format accepted by ZoneId.of(String) is not exactly the same as that of TimeZone.getTimeZone(String), but as the Javadoc of ZoneId.of(String) says, most region IDs are compatible.

like image 21
Jaan Avatar answered Oct 18 '25 15:10

Jaan