FYI, the Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes.
Using java.time
The LocalDate
class is java.time is akin to the Joda-Time LocalDate
. A date-only value, without time-of-day and without time zone. One difference is that java.time eschews constructors for factory methods.
LocalDate start = LocalDate.of( 2011 , 11 , 8 );
LocalDate stop = LocalDate.of( 2012 , 5 , 1 );
Collect the Mondays.
List<LocalDate> mondays = new ArrayList<>();
The TemporalAdjuster
interface provides for classes that manipulate date-time values. The TemporalAdjusters
class (note the plural name) provides various implementations. We want the nextOrSame
and next
adjusters, passing the desired DayOfWeek.MONDAY
enum object.
LocalDate monday = start.with( TemporalAdjusters.nextOrSame( DayOfWeek.MONDAY ) );
while( monday.isBefore( stop ) ) {
mondays.add( monday );
// Set up the next loop.
monday = monday.plusWeeks( 1 );
}
By the way, usually the wise approach in handling a span of time is Half-Open where the beginning is inclusive while the ending is exclusive. So in the code above we are running up to, but not including, the stop
date.
If the ending is inclusive, use the negation of isAfter
e.g.
while( !monday.isAfter( stop ) ) {
//...
}
Here, monday
is not after stop
means it is before or up to stop
.
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
.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?