Using java.time
The modern approach uses the java.time classes.
a given date
The LocalDate
class represents a date-only value without time-of-day and without time zone.
LocalDate ld = LocalDate.of( 2016 , Month.JANUARY , 23 );
the first Sunday of a calendar month
The TemporalAdjuster
interface provides for classes that manipulate date-time values. But understand that java.time uses immutable objects. Rather than alter the fields of an object (“mutating”), we instantiate a fresh object with values based on those of the original object.
The TemporalAdjusters
class (note the plural s
) provides handy implementations of TemporalAdjuster
. These include getting the first, last, or nth day-of-week of a month. We want first Sunday of the month, so we specify the predefined enum object DayOfWeek.SUNDAY
.
LocalDate firstSundayOfMonth = ld.with( TemporalAdjusters.firstInMonth( DayOfWeek.SUNDAY ) );
end on the Saturday following the last day of the last month
We have another TemporalAdjuster
to get the last day of the month.
LocalDate lastLocalDateOfMonth = ld.with( TemporalAdjusters.lastDayOfMonth() ) ;
And another adjuster to get the same or next day-of-week.
LocalDate nextOrSameSaturdayOfEndOfMonth =
lastLocalDateOfMonth .with( nextOrSame( DayOfWeek.SATURDAY ) ) ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
- Java SE 8 and SE 9 and later
- Built-in.
- Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6 and SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.