tl;dr
LocalDate.now(
ZoneId.of( "Africa/Tunis" )
)
.withNextOrSame( DayOfWeek.SUNDAY )
.plusWeeks( 1 )
java.time
The modern approach uses the java.time classes.
Today
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 pseudo-zones such as EST
or IST
as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
The LocalDate
class represents a date-only value without time-of-day and without time zone.
LocalDate today = LocalDate.now( z );
Day of week
To find the next Sunday on or after today, use a TemporalAdjuster
implementation found in the TemporalAdjusters
class.
LocalDate nextOrSameSunday = today.withNextOrSame( DayOfWeek.SUNDAY ) ;
Collection
Collect a dozen such sequential dates.
int countWeeks = 12 ;
List< LocalDate > sundays = new ArrayList<>( 12 ) ;
for( int i = 0 , i < countWeeks , i ++ ) {
sundays.add( nextOrSameSunday.plusWeeks( i ) ) ; // + 0, + 1, + 2, … , + 11.
}
Tip: Focus on working with representative data objects rather than mere Strings. When needed for display, loop your collection and generate strings with a call to toString
or format( DateTimeFormatter )
.
for( LocalDate ld : sundays ) { // Loop each LocalDate in collection.
String output = ld.toString() ; // Generate a string in standard ISO 8601 format.
…
}
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.