♻ Ode to Joda-Time

| No TrackBacks

After using a really well-designed API for a while, I feel obliged to thank its creators. Thank you, Joda-Time.

To paraphrase a colleague: Joda-Time seems way over-designed at first glance, but once you start using it in an application, you realize everything is there for a purpose.

Essentially, Joda-Time replaces Java’s clunky Date and Calendar-based way of manipulating times. Everything is immutable (though you can use mutable variants, if you want), and every method you need is there when you content assist. Often, there are different ways to get what you need, too:

DateTime now = new DateTime();
DateTime yesterday = now.minusDays(1);
DateTime anotherYesterday = now.minus(Days.ONE);
assert(yesterday.equals(anotherYesterday));

One of the great features is how the API separates the notions of time between two DateTimes (an Interval) and our normal notion of calendar time (a Period). (There’s also another notion of time as a fixed number of milliseconds called a Duration.) The names are confusing at first, but I swear they make sense.

DateTime adamsEpoch = 
    new DateTime(1986, 7, 14, 22, 26, 0, 0, 
    DateTimeZone.forId("America/Chicago"));
DateTime now = new DateTime();
Interval adamsLife = 
    new Interval(adamsEpoch, now);
DateTime y2k = new DateTime(2000, 1, 1, 0, 0, 0, 0);
Interval twentiethCentury = 
    new Interval(y2k.withYear(1900), y2k);
Interval adamInTwentiethCentury = adamsLife.overlap(y2k);
DateTime twentyFifthBirthday = 
    adamsEpoch.plus(Years.25); // Using the Years Period

Joda-Time also lets you format your dates in pretty much any conceivable way and handles all sorts of time zone and calendar quirks gracefully, but I won’t get into that here.

The short version: Joda-Time saves everyone time.

No TrackBacks

TrackBack URL: http://tr.ashcan.org/mt/mt-tb.cgi/215