Wednesday, December 16, 2009

Retrieving Time Zone's DST information in Java

I have worked extensively with times. By time, I mean the software representation of time and the mapping of various concepts surrounding this tangible entity.

Handling of Time Zone, Daylight Saving Time (DST) is a pretty important use case in most softwares. All programming languages have libraries specifically designed to manipulate time easily. However, the implementation of these APIs isn't standardized and therefore developers have to go through a learning curve in order to use these APIs effectively and correctly. But the fact is that most of the developers take the concept for granted and are contend to directly use the libraries without learning the concepts properly.

Web is full of these resources and help can be found for learning the concepts and correctly utilizing the APIs in different languages.

There's one small use case in Java for which I couldn't find any assistance and that simply is: retrieving DST details for a particular Time Zone in Java.

The java.util.TimeZone does contain DST information, however it is not exposed in a direct manner in any of the TimeZone related classes. Internally, TimeZone calculates DST in SimpleTimeZone class (an implementation of TimeZone), which is accessed within TimeZone via ZoneInfo class' static methods.

Look here for the DST related private members of java.util.SimpleTimeZone.

Fortunately, these fields are visible through the toString() method of this class. Have a look at the source.

For convenience I'm providing a simple listing to extract out the DST information of a particular TimeZone:

This approach only works if 'mode' is taken into consideration. As the example is written, it only works for 'mode' = DOM_MODE (0-Day of Month). For other modes, the startDay and endDay values are NOT the day of the month and must be adjusted. See private method java.util.SimpleTimeZone.getTransition.