tl;dr
LocalDate.now( ZoneId.of( "Pacific/Auckland" ) )
.with(
TemporalAdjusters.previousOrSame( DayOfWeek.SUNDAY )
)
java.time
The modern approach uses java.time classes.
Get current moment in UTC.
Instant instant = Instant.now() ;
If you care about day-of-week, you care about date. Determining a date requires a time zone. For any given moment the date varies around the globe by zone.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = instant.atZone( z ) ; // Same point on the timeline, different wall-clock time.
To focus on date-only without time-of-day, extract a LocalDate
.
LocalDate ld = zdt.toLocalDate() ;
To adjust into other moments, use a TemporalAdjuster
. Find implementations in TemporalAdjusters
.
LocalDate previousOrSameSunday = ld.with(
TemporalAdjusters.previousOrSame( DayOfWeek.SUNDAY )
) ;
…and…
LocalDate nextOrSameSunday = ld.with(
TemporalAdjusters.nextOrSame( DayOfWeek.SUNDAY )
) ;
To compare, look for isBefore
, isAfter
, isEqual
, and equals
methods on the various java.time classes.
thisLocalDate.isBefore( thatLocalDate)
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?
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.