Nicolas Frankel is an IT consultant with 10 years experience in Java / JEE environments. He likes his job so much he writes technical articles on his blog and reviews technical books in his spare time. He also tries to find other geeks like him in universities, as a part-time lecturer. Nicolas is a DZone MVB and is not an employee of DZone and has posted 221 posts at DZone. You can read more from them at their website. View Full User Profile

Ways of comparing Date Objects in Java

06.11.2012
| 12648 views |
  • submit to reddit
Let's face it, compairing Date objects in Java is complex and as well as error-prone. This is the case in standard code, but this is also the case in testing code, where we regularly need to create Date objects that point at specific instant in time, to be our reference in comparison.

The good ol' deprecated way

In test code, I've no qualms about using deprecated methods. So, I used the old Date constructor to initialize dates:
Date date = new Date(112, 5, 3);
  Pro: it's concise. Con: it really isn't intuitive and you need a good knowledge of the Java API to know the first parameter is the year minus 1900 and the second is the month count (beginning at 0, for January). It's almost a surprise to learn the last parameter is simply... the day of the month.

The canonical way

Since Java 1.1, Calendar was introduced in the Java API to dissociate between an instant in time (the date) and its view in a specific referential (the calendar). The following snippet is a naive way to obtain the same result as above.
Calendar calendar = Calendar.getInstance();

calendar.set(YEAR, 2012);
calendar.set(MONTH, JUNE);
calendar.set(DAY_OF_MONTH, 3);
  It's not only more verbose, it's also a mistake: hours, minutes and the rest are not 0 (depending on the exact creation time of the calendar) so using equals() here will return false. Here's the correct code:
Calendar calendar = Calendar.getInstance();

calendar.set(YEAR, 2012);
calendar.set(MONTH, JUNE);
calendar.set(DAY_OF_MONTH, 3);
calendar.set(HOUR_OF_DAY, 0);
calendar.set(MINUTE, 0);
calendar.set(SECOND, 0);
calendar.set(MILLISECOND, 0);
  It defeats brevity purpose, to say the least ;-)

Apache Commons Lang

Apache Commons provides since ages different utility libraries that help develop in Java. One of such library is Apache Commons Lang, which aims at providing code that would merit being part of the Java API. In our case, the DateUtils class let us shorten the previous code, while keeping its readibility:
Calendar calendar = Calendar.getInstance();

calendar.set(YEAR, 2012);
calendar.set(MONTH, JUNE);
calendar.set(DAY_OF_MONTH, 3);
calendar = DateUtils.truncate(calendar, DAY_OF_MONTH);
Even better, DateUtils let us work directly on Date objects, to make the following alternative also possible:
Date date = new Date();

date = DateUtils.setYears(date, 2012);
date = DateUtils.setMonths(date, JUNE);
date = DateUtils.setDays(date, 3);
date = DateUtils.truncate(date, DAY_OF_MONTH);
Note that it leaves parameters untouched, enforcing the immutability dear to Functional Programing proponents. Pro: we use the standard Java API. Con: none. And yet, wouldn't a full-fledged DSL feel somewhat more right?

Joda Time

The final option is to use Joda Time, which aims at being a replacement for Date and Calendar. It also has spawned the JSR-310"a new and improved date and time API for Java", that should be part of Java 8 (it was originally scheduled for Java 7). A whole article (or even a mini-guide) could be dedicated to Joda Time. For our present concern, the following snippet can advantageously replace our original one:
DateMidnight dm = new DateMidnight(2012, 6, 3);
  Back to square one, it seems: clear and concise. And yet, the parameters self explanatory, no real need to regularly check the JavaDocs to see how to initialize the year. Besides, the semantics of the class name are clear. Finally, the toDate() method let us bridge to the standard Java API.

Conclusion

The conclusion is your own. As for myself, I regularly use Apache Commons Lang, but I'm leaning toward Joda Time these days. The code is available here as a Eclipse/Maven project archive. Note: if you need to work with business days, I've been recently made aware of ObjectLab Kit. I haven't used it yet, and feedbacks are welcomed.
Published at DZone with permission of Nicolas Frankel, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Andreas Schilling replied on Mon, 2012/06/11 - 1:56am

while it has a slightly more complex setup phase (especially concerning integration with hibernate or the like) we definitely go for JodaTime. unfortunately no project yet has been completely based on it, but the next one surely will. the result however always was, that business logic based on JodaTime was faster done and with less bugs :-)

Greg Allen replied on Mon, 2012/06/11 - 6:07am

If your problem is just how to easily and concisely create literal Date instances, I like to use sql Date:

java.sql.Date.valueOf("2011-12-31")

Only really appropriate for timeless Dates of course.

 

Sylvain Brocard replied on Mon, 2012/06/11 - 8:17am

Yes, JodaTime is really interesting to work with Date.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.