tl;dr
LocalDate.now( ZoneId.of( "Pacific/Auckland" ) )
.minusYears( 1 )
.previousOrSame( DayOfWeek.MONDAY )
java.time
The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes.
LocalDate
The LocalDate
class represents a date-only value without time-of-day and without time zone.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
Specify a proper time zone name in the format of continent/region
, such as America/Montreal
, Africa/Casablanca
, or Pacific/Auckland
. Never use the 3-4 letter abbreviation such as EST
or IST
as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );
Year ago
The java.time classes can do math.
LocalDate yearAgo = today.minusYears( 1 ) ;
Day of week
Determine today’s day-of-week.
DayOfWeek dow = today.getDayOfWeek() ;
To adjust into different date-time values, use a TemporalAdjuster
implementation. One for your purpose is found in TemporalAdjusters
class.
LocalDate previousOrSameDay = yearAgo.with( TemporalAdjusters.previousOrSame( dow ) ;
Or get the following day-of-week.
LocalDate nextOrSameDay = yearAgo.with( TemporalAdjusters.nextOrSame( dow ) ;
You need to define your rules for going to next or previous.
Set< DayOfWeek > previous = EnumSet.range( DayOfWeek.MONDAY , DayOfWeek.THURSDAY ) ; // Collect Mon, Tue, Wed, and Thu.
Set< DayOfWeek > next = EnumSet.complementOf( previous) ; // Collect Fri, Sat, Sun.
Then test your day-of-week.
LocalDate ld ;
if( previous.contains( dow ) ) {
ld = yearAgo.with( TemporalAdjusters.previousOrSame( dow ) ;
} else if ( next.contains( dow ) ) {
ld = yearAgo.with( TemporalAdjusters.nextOrSame( dow ) ;
} else {
// Handle unexpected error.
System.out.println( "Unexpectedly reached IF-ELSE for day-of-week: " + dow ) ;
}
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.