Haven’t got the time? Joda Java Date-Time framework does….
September 13, 2010 3 Comments
Raise your hand if you have a DateUtil class or you wince every time you have to work with Java dates. Now ask yourself are you the type of person who would rather struggle around with it and write it yourself or are you enterprising enough to look for another solution. I know most Java developers complain about framework fatigue these days, but I wouldn’t trade the hundreds of frameworks out there just to have to go back to the days when I had to do it all myself. Joda Java Date Time framework is a great example of why I like frameworks.
Joda has all the date utilities you will ever need to manipulate time and dates in Java. Let’s take a look at some of the examples straight from the framework’s web site.
public boolean isAfterPayDay(DateTime datetime) {
if (datetime.getMonthOfYear() == 2) { // February is month 2!!
return datetime.getDayOfMonth() > 26;
}
return datetime.getDayOfMonth() > 28;
}
public Days daysToNewYear(LocalDate fromDate) {
LocalDate newYear = fromDate.plusYears(1).withDayOfYear(1);
return Days.daysBetween(fromDate, newYear);
}
public boolean isRentalOverdue(DateTime datetimeRented) {
Period rentalPeriod = new Period().withDays(2).withHours(12);
return datetimeRented.plus(rentalPeriod).isBeforeNow();
}
public String getBirthMonthText(LocalDate dateOfBirth) {
return dateOfBirth.monthOfYear().getAsText(Locale.ENGLISH);
}
After I found Joda time I gutted my DateUtil class and just had the implementations of the utility methods call Joda features. The framework is extremely rich and it has several benefits, two of which are;
1. It simplifies the manipulations of Date and Time in a logical way
2. It alleviates the performance penalties that result from improper use of the Date and Calendar objects in Java.
So as I have said many times, don’t reinvent the wheel. Go grab the Joda time jar and toss all that crappy code in your DateUtil…I did….