Should I use Java date and time classes or go with a 3rd party library like Joda Time?

user14070 picture user14070 · Feb 26, 2009 · Viewed 29k times · Source

I'm creating a web based system which will be used in countries from all over the world. One type of data which must be stored is dates and times.

What are the pros and cons of using the Java date and time classes compared to 3rd party libraries such as Joda time? I guess these third party libraries exist for a good reason, but I've never really compared them myself.

Answer

Jon Skeet picture Jon Skeet · Feb 26, 2009

EDIT: Now that Java 8 has been released, if you can use that, do so! java.time is even cleaner than Joda Time, in my view. However, if you're stuck pre-Java-8, read on...

Max asked for the pros and cons of using Joda...

Pros:

  • It works, very well. I strongly suspect there are far fewer bugs in Joda than the standard Java libraries. Some of the bugs in the Java libraries are really hard (if not impossible) to fix due to the design.
  • It's designed to encourage you to think about date/time handling in the right way - separating the concept of a "local time" (e.g "wake me at 7am wherever I am") and an instant in time ("I'm calling James at 3pm PST; it may not be 3pm where he is, but it's the same instant")
  • I believe it makes it easier to update the timezone database, which does change relatively frequently
  • It has a good immutability story, which makes life a lot easier IME.
  • Leading on from immutability, all the formatters are thread-safe, which is great because you almost always want to reuse a single formatter through the application
  • You'll have a head-start on learning java.time in Java 8, as they're at least somewhat similar

Cons:

  • It's another API to learn (although the docs are pretty good)
  • It's another library to build against and deploy
  • When you use Java 8, there's still some work to migrate your skills
  • I've failed to use the DateTimeZoneBuilder effectively in the past. This is a very rare use case though.

To respond to the oxbow_lakes' idea of effectively building your own small API, here are my views of why this is a bad idea:

  • It's work. Why do work when it's already been done for you?
  • A newcomer to your team is much more likely to be familiar with Joda than with your homegrown API
  • You're likely to get it wrong for anything beyond the simplest uses... and even if you initially think you only need simple functionality, these things have a habit of growing more complicated, one tiny bit at a time. Date and time manipulation is hard to do properly. Furthermore, the built-in Java APIs are hard to use properly - just look at the rules for how the calendar API's date/time arithmetic works. Building anything on top of these is a bad idea rather than using a well-designed library to start with.