java.time
The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. The java.time framework is built into Java 8 and later.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to useā¦).
java.time.LocalDate
The LocalDate
class represents a date-only value without time-of-day and without time zone.
You can specify the year, month, and day-of-month.
LocalDate ld = LocalDate.of( 2016 , 1 , 15 );
You can switch months. The java.time classes use the Immutable Objects pattern, so a new fresh object is generated based on values of the original.
LocalDate september = ld.withMonth( 9 ); // 1-12 for January-December.
You can add/subtract months.
LocalDate nextMonth = ld.plusMonths( 1 );
LocalDate priorMonth = ld.minusMonths( 1 );
You can take any LocalDate and adjust the day to the 15th.
LocalDate today = LocalDate.now( ZoneId.of( "America/Montreal" ) );
LocalDate fifteenthThisMonth = today.withDayOfMonth( 15 );
Trap for a DateTimeException
being thrown in the case of a day-of-month number invalid for that month, such as 31 for February.
By the way, you may find the YearMonth
or MonthDay
classes handy, and the Month
enum too.
Joda-Time
If you must use Joda-Time, it offers a LocalDate
class quite similar to java.time.LocalDate
.
LocalDate ld = new LocalDate( 2016 , 1 , 7 );
LocalDate fifteenthSameMonth = ld.withDayOfMonth( 15 );