Friday, October 31, 2008

Java Tip: java.util.Date.after(Date date) != java.util.Calendar.after(Object obj)

I'm working on some date logic where I am using instances of java.util.Calendar objects and instances of java.util.Date objects.

The Calendars are calculated dates, and the Date fields are retrieved from the database.

In almost every case I've performed a comparison by invoking either the before or after method on the Date objects. In most cases it would be something like:
if(date.before(calendar.getTime())) {
doSomething();
}

I just realized that I fell into a nasty hole confusing my calendar with my date: i.e.

if(calendar.after(date)) {
doSomething();
}

these two expressions are not equal. The Calendar before and after methods will return false if the argument is not an instance of Calendar. The Date before and after methods will only allow an instance of date as an argument.

That was not fun to find. Fortunately I found it while I was trying to get my test code coverage above 90%. This defect could have cost us time in User Acceptance testing and could have possibly made it as far as production.

I will definitely mind my P's and Q's when dealing with Dates and Calendars.

No comments: