Better Java Dates, Times & Calendars with Joda-Time

Anyone who has used Java to manipulate Dates will know that it's one of the most frustrating parts of the core APIs - it should just be so easy!

As an example, here is one way to create a 'date of birth' Date - in this object we want the time part of the Date to be all zeros (midnight):

import java.util.Calendar;
import java.util.Date;

Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.set(2004, Calendar.JULY, 10);
Date dob = calendar.getTime();
There are a few gotchas to be aware of here, first is that you can't specify the month value as just "7" or "07" as that would give the month as August (as month 0 = January!) and the other is that without the call to clear() the time part will be set to the time when the Calendar.getInstance() was called.

Now compare this to creating a 'date of birth' Date object using Joda-Time:
import org.joda.time.DateMidnight;

Date dob = new DateMidnight(2004, 07, 10).toDate();
The DateMidnight class indicates that the time part will be zeros (more explicit than the "clear()" method) and you don't have to use any constants to build up the months.

The Joda-Time package is rammed full of useful bits like this, including instants, periods, intervals, durations, etc. as well as full calendar support and the ability to 'freeze time' (very useful for unit testing).

It's a fantastic package and should be considered a replacement for the cumbersome java.util.Calendar class.

Technorati Tags: , , , ,

3 comments:

JodaStephen said...

For a date of birth, I'd recommend the LocalDate class.

Bill Comer said...

second JodaStephen on LocalDate and why not just drop using java.util.Date altogether other than when you have to interface to external APIs.

The FreezeTime utility is excellent for testing.

igavehimtherope said...

It's so good they're bringing 'I can't believe it's not Joda-Time' into Java 7:

http://jcp.org/en/jsr/detail?id=310