TL; DR
java.time.LocalDate.of( 2018 , Month.JANUARY , 23 ) // A date-only class in the modern *java.time* classes that supplant both Joda-Time and the troublesome old date-time classes. .with( TemporalAdjusters.next( DayOfWeek.FRIDAY ) // Nifty `TemporalAdjuster` implementation for moving to another date. Immutable Objects pattern means a new object is returned based on the original which remains unmodified. ) .isBefore( // Compare `LocalDate` objects with `isBefore`, `isAfter`, and `isEqual`. LocalDate.of( 2018 , Month.FEBRUARY , 27 ); )
java.time
FYI, the Joda-Time project is now in maintenance mode , and the team advises switching to the java.time classes.
Define your stop and run the LocalDate objects.
LocalDate start = LocalDate.of( 2018 , Month.JANUARY , 23 ); LocalDate stop = LocalDate.of( 2018 , Month.FEBRUARY , 27 ); // TODO: Verify start.isBefore( stop ).
Collect the Friday dates we find. You can optimize the collection setting a bit.
// Pre-size the collection. int initialCapacity = ( int ) ( ChronoUnit.WEEKS.between( start , stop ) + 2 ); // Adding two for good measure. List < LocalDate > fridays = new ArrayList <>( initialCapacity );
Determine the first Friday using the start date, if it is Friday itself. Use the pair of TemporalAdjuster implementations proposed in the TemporalAdjusters class: nextโ(DayOfWeek) and nextOrSameโ(DayOfWeek) . Pass the desired day of the week through the DayOfWeek enumeration, seven predefined objects, one for each day of the week from Monday to Sunday.
LocalDate friday = start.with( TemporalAdjusters.nextOrSame( DayOfWeek.FRIDAY ) ); while ( friday.isBefore( stop ) ) { fridays.add( friday ); // Remember this Friday date. // Setup next loop. friday = friday.with( TemporalAdjusters.next( DayOfWeek.FRIDAY ) ); } System.out.println( "From " + start + " to " + stop + " = " + fridays );
From 2018-01-23 to 2018-02-27 = [2018-01-26, 2018-02-02, 2018-02-09, 2018-02-16, 2018-02-23]
About java.time
The java.time framework is built into Java 8 and later. These classes supersede the nasty old legacy datetime classes such as java.util.Date , Calendar and SimpleDateFormat .
The Joda-Time project, now in maintenance mode , we recommend switching to the java.time classes.
To learn more, see the Oracle Tutorial . And search for qaru for many examples and explanations. JSR 310 specification .
You can exchange java.time objects directly with your database. Use a JDBC driver that conforms to JDBC 4.2 or later. No strings needed, no java.sql.* Classes needed.
Where to get java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proof of possible future additions to java.time. Here you can find useful classes such as Interval , YearWeek , YearQuarter and more .