ONJava.com -- The Independent Source for Enterprise Java
oreilly.comSafari Books Online.Conferences.


AddThis Social Bookmark Button
  Making Sense of Java's Dates
Subject:   badly designed, over-complicated garbage
Date:   2008-04-30 16:04:00
From:   Anonymous8888
Response to: Minor correction

The java calendar class is just *horrible* to use and unfortunately, normally unavoidable.

Problem 1: Why can't I do this?

Calendar cal = new Calendar();

I can do this...
Calendar cal = new GregorianCalendar();

But seeing as GregorianCalendar is the only subclass of Calendar, it makes no sense to prevent me from doing this!

Problem 2: This isn't specific to the calendar class really, but a general moan about java API designers - you essentially have to know the workings of the black box in order to use it. Eg.

cal.set(Calendar.MONTH, 7);

Yuk. The documentation of the class isn't particularly clear, leaving you to hunt for examples to copy.

Problem 3: Complete inconsistency and lack of intuitiveness - Months are zero-based, but Days (and years) are 1-based. This means that the following...

cal.set(Calendar.MONTH, 4);
cal.set(Calendar.DAY_OF_MONTH, 4);

...gives the 4th of March!!! I've been tripped up by this SO many times, especially as if you're going to actually *use* this date with another system (such as using it with a database) you have to remember to add one.