Is there a usablility to get all dates between two dates in the new java.time
API?
Let\'s say I have this part of code:
Java 9
In Java 9, the LocalDate
class was enhanced with the LocalDate.datesUntil(LocalDate endExclusive) method, which returns all dates within a range of dates as a Stream<LocalDate>
.
List<LocalDate> dates = startDate.datesUntil(endDate).collect(Collectors.toList());
First you can use a TemporalAdjuster
to get the last day of the month. Next the Stream
API offers Stream::iterate which is the right tool for your problem.
LocalDate start = LocalDate.now();
LocalDate end = LocalDate.now().plusMonths(1).with(TemporalAdjusters.lastDayOfMonth());
List<LocalDate> dates = Stream.iterate(start, date -> date.plusDays(1))
.limit(ChronoUnit.DAYS.between(start, end))
.collect(Collectors.toList());
System.out.println(dates.size());
System.out.println(dates);