Using java.time
The Joda-Time project is now in maintenance mode , with the team advising switching to the java.time classes.
half open
Working with a date usually uses the Half-Open method to determine the amount of time when the beginning is inclusive and the ending is exceptional. I believe that the consistent use of this approach both in your code and in your user business makes life easier, avoiding inaccuracies that can lead to misunderstandings or errors.
The java.time classes use the Half-Open approach. Keep this in mind when using Period , Duration and ChronUnit .
LocalDate start = LocalDate.of( 2017 , 1 , 23 ); LocalDate stop = LocalDate.of( 2017 , 2 , 14 ); List<LocalDate> dates = new ArrayList<>( (int) ChronoUnit.DAYS.between( start , stop ) ) ; LocalDate ld = start ; while( ld.isBefore( stop ) ) { // Half-open approach, ending is exclusive. dates.add( ld ); // Set up the next loop. ld = ld.plusDays( 1 ); }
If you insist on including this end date, add an entry day.
LocalDate stop = LocalDate.of( 2017 , 2 , 14 ).plusDays( 1 ); // Effectively making ending date inclusive.
... or (A) change the logic of the while test from isBefore to ! isAfter ! isAfter and (B) add it to the initial capacity of the ArrayList .
List<LocalDate> dates = new ArrayList<>( ( (int) ChronoUnit.DAYS.between( start , stop ) ) + 1 ) ; // Add one to accommodate inclusive ending (*not* Half-Open). LocalDate ld = start ; while( ! ld.isAfter( stop ) ) { // Ending is inclusive (*not* Half-Open). So using "not after" logic rather than "is before". dates.add( ld ); // Set up the next loop. ld = ld.plusDays( 1 ); }
Stream<LocalDate>
By the way, this code is simplified in Java 9, where you can get the Stream<LocalDate from LocalDate::datesUntil . This call returns a sequential ordered stream of dates.
A variant of this method allows you to specify a quantity for increasing dates. So, for example, instead of defaulting a one-time gain, you can increase by two to get it every day.
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 .
Where to get java.time classes?
- Java SE 8 and SE 9 and later
- Built in.
- Part of the standard Java API with integrated implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6 and SE 7
- Android
The ThreeTen-Extra project extends java.time with additional classes. This project is proof of possible future additions to java.time. Here you can find useful classes such as Interval , YearWeek , YearQuarter and more .