Sunday, September 30, 2007

Java Date, Calendar

Of all the dimensions, time is the most difficult to deal with. Here are my notes on the Java Date and Calendar classes. I will do a separate post on time zone.

Date is an absolute measure of the time. It is a measure of the number of milliseconds that have elapsed since the Epoch. Date is the same where ever you are on earth. As far as I know the the only inaccuracy is that it does not account for leap seconds, but then we have not had many leap seconds recently.

Date has no concept of time zone. You can safely send a Date from one system to another in a different time zone and the Date is unchanged and still correct. You may be confused by the fact that calling toString on Date in some versions of Java will produce a localized string with the time in your time zone. The toString call does this by asking the environment for the time zone. I think that this is very confusing behavior. It would be better if toString displayed the time according to the ISO 8601 standard.

Calender is a Date and a TimeZone. The TimeZone is used when making changes to the time value in the date. Realize that there is a difference between adding 24 hours to a Date and adding a day. If the day happens to span the time change to or from daylight savings time, you have to add 23 or 25 hours to the Date to get to the same time in the next day.

Calendar also deals with other time conundrums like adding a month. Say you are on the 31 of January and add a month, where do you end up? Calendar can give you the 28th of February if you set it up right. Calendar does have its limitations, you cannot add half a day and you have to be careful to use the correct unit when rolling time.

Here is a Java code fragment to format a Date correctly:

SimpleDateFormat ISO8601 =
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
ISO8601.setTimeZone(TimeZone.getTimeZone("UTC"));
String zuluTime = ISO8601.format(new Date());