Using java.time
The modern approach is with the java.time classes that supplant the troublesome old legacy date-time classes.
The java.time classes are much easier to work with. In particular, they remove the ambiguity raised in the Question. You can explicitly ask either for the earlier Sunday or for the later Sunday.
The LocalDate
class represents a date-only value without time-of-day and without time zone.
The Month
enum provides a dozen pre-defined objects, one for each month of the year. These enum objects are safer to use, but you can instead use a plain number for the month. Unlike the legacy classes, these months have sane numbering, 1-12 for January-December.
LocalDate localDate = LocalDate.of( 2009 , Month.AUGUST, 22 );
The TemporalAdjuster
interface provides for manipulation of date-time values. The TemporalAdjusters
class (note the plural s
) provides several handy implementations.
The previous
& next
adjusters exclude the date itself from consideration. The previousOrSame
& nextOrSame
methods return the date in question if it is indeed the desired day-of-week.
The DayOfWeek
enum provides seven pre-defined objects, one for each day of the week.
LocalDate previousSunday = localDate.with( TemporalAdjusters.previous ( DayOfWeek.SUNDAY ));
LocalDate previousOrSameSunday = localDate.with( TemporalAdjusters.previousOrSame ( DayOfWeek.SUNDAY ));
LocalDate nextSunday = localDate.with( TemporalAdjusters.next ( DayOfWeek.SUNDAY ));
LocalDate nextOrSameSunday = localDate.with( TemporalAdjusters.nextOrSame ( DayOfWeek.SUNDAY ));
Dump to console.
System.out.println ("localDate: " + localDate + " ( " + localDate.getDayOfWeek ().getDisplayName ( TextStyle.FULL, Locale.US ) + " )");
System.out.println ("previousSunday: " + previousSunday );
System.out.println ("nextSunday: " + nextSunday );
localDate: 2009-08-22 ( Saturday )
previousSunday: 2009-08-16
nextSunday: 2009-08-23
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.