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):
Now compare this to creating a 'date of birth' Date object using Joda-Time:
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: Java, Date, Calendar, JodaTime, Andrew Beacock
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;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
import java.util.Date;
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.set(2004, Calendar.JULY, 10);
Date dob = calendar.getTime();
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;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.
Date dob = new DateMidnight(2004, 07, 10).toDate();
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: Java, Date, Calendar, JodaTime, Andrew Beacock
Comments
The FreezeTime utility is excellent for testing.
http://jcp.org/en/jsr/detail?id=310