Joda-Time provides a quality replacement for the Java date and time classes. The design allows for multiple calendar systems, while still providing a simple API.
Joda-Time is a library which can be used as a replacement for the Java date and time classes. From Java SE 8 onwards, users are asked to migrate to java.time
(JSR-310).
Sample Code
This sample is provided from code written as part of an interval type enum
which could calculate a series of dates at that interval. It provides a great example of what it looks like to call some common methods on Joda's DateTime
object.
public DateTime getNextDate(DateTime dt, int interval) {
switch(this) {
case SECOND:
return dt.plusSeconds(interval);
case MINUTE:
return dt.plusMinutes(interval);
case HOUR:
return dt.plusHours(interval);
case DAY:
return dt.plusDays(interval);
case WEEK:
dt = dt.plusDays(3).plusWeeks(interval - 1);
return dt.withDayOfWeek(6);
case MONTH:
dt = dt.plusDays(3).plusMonths(interval - 1);
return dt.withDayOfMonth(dt.dayOfMonth().getMaximumValue());
case QUARTER:
dt = dt.plusDays(3).plusMonths((interval - 1) * 3);
dt = dt.plusMonths((3 - (dt.getMonthOfYear() % 3)) % 3);
return dt.withDayOfMonth(dt.dayOfMonth().getMaximumValue());
case YEAR:
dt = dt.plusDays(3).plusYears(interval - 1);
return dt.withDayOfYear(dt.dayOfYear().getMaximumValue());
}
return dt;
}
Some helpful SO posts
- Should I use Java date and time classes or go with a 3rd party library like Joda Time?
- Joda: what's the difference between Period, Interval and Duration?
- Convert from java.util.date to JodaTime