Simplifying Date/Time Calculations with Date4J
In Chapter: Social Networking
Author: Ian Darwin ('idarwin')
You want a simple, sensible Date/Time API.
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.
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 ) 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.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
To get started, download the JAR file from  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 .
The project web site is .
If you found this recipe useful, why not
buy the book
and have the whole collection always at hand?"