Java Tip #5: Use Apache Commons DateUtils when dealing with dates
Tip #5 in my Java Tips series is again focussing around the Apache Commons framework. In the same manner the StringUtils simplifies many common operations on Strings (see also Java Tip #3), DateUtils ease some of the pain when working with Java Date objects.
Advice
Use Commons DateUtils to manipulate and calculate dates.
Code-Example
Before
...
private static Date add(Date date, int field, int amount) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(field, amount);
return cal.getTime();
}
...
public static Date getNextDay() {
return add(getCurrentDay(), Calendar.DATE, 1);
}
...
After
...
public static Date getNextDay() {
return DateUtils.addDays(getCurrentDay(), 1);
}
...
Benefit
Huge readability gain. By using DateUtils for calculating and manipulating Dates the code footprint gets smaller and easier to read. Furthermore by using explicit methods like addDays() it is clearer which part of a date is to be modified, compared to the partly ambiguous constants in the Calendar class. DateUtils also contains methods to round or truncate Dates to certain parts of the date, eg. truncate() by Calendar.HOUR sets minutes, seconds and miliseconds to zero.
Remarks
None.