Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
GitHub logo Twitter logo OReilly Book Cover Art

Simplifying Date/Time Calculations with Date4J

Published? true
FormatLanguage: WikiFormat

Problem:

You want a simple, sensible Date/Time API.

Solution:

Use Date4J, the small, sensible Date/Time API for Java. Unlike JSR-310 it does not depend on Java features that didn't make it into Android, so it "just works" on Android.

Discussion:

While the problems with _java.util_ Date and Calendar class are well known, Java 8's solution is not available on Android (see 4622 for discussion).

Date4J provides most of its functionality in one class, _DateTime_. This includes the ability to do arithmetic on dates, as well as to create (and interrogate for) Date-only, Time-only and Date+Time objects.

Here are some examples (cribbed from [1]) to show you the level of complexity of the kind of calculations that are _built in_ to Date4J's DateTime class:


 DateTime dateAndTime = new DateTime("2010-01-19 23:59:59");
 DateTime dateAndTime = new DateTime("2010-01-19T23:59:59.123456789");
 DateTime dateOnly = new DateTime("2010-01-19");
 DateTime timeOnly = new DateTime("23:59:59");
 DateTime dateOnly = DateTime.forDateOnly(2010,01,19);
 DateTime timeOnly = DateTime.forTimeOnly(23,59,59,0);
 DateTime dt = new DateTime("2010-01-15 13:59:15");
 boolean leap = dt.isLeapYear(); //false
 dt.getNumDaysInMonth(); //31
 dt.getStartOfMonth(); //2010-01-01, 00:00:00.000000000
 dt.getEndOfDay(); //2010-01-15, 23:59:59.999999999
 dt.format("YYYY-MM-DD"); //formats as '2010-01-15'
 dt.plusDays(30); //30 days after Jan 15
 dt.numDaysFrom(someDate); //returns an int
 dueDate.lt(someDate); //less-than
 dueDate.lteq(someDate); //less-than-or-equal-to

To get started, download the JAR file from [2] or, if you build with Maven 4137, my repackaging for Maven is available in source form at http://github.com/IanDarwin/date4j.git and you can find the latest Maven Central co-ordinates at [3].

See Also:

The project web site is [1].