Patrick Patrick - 5 months ago 92
Java Question

Java 8 LocalDate - How do I get all dates between two dates?

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:

@Test
public void testGenerateChartCalendarData() {
LocalDate startDate = LocalDate.now();

LocalDate endDate = startDate.plusMonths(1);
endDate = endDate.withDayOfMonth(endDate.lengthOfMonth());
}


Now I need all dates between
startDate
and
endDate
.

I was thinking to get the
daysBetween
of the two dates and iterate over:

long daysBetween = ChronoUnit.DAYS.between(startDate, endDate);

for(int i = 0; i <= daysBetween; i++){
startDate.plusDays(i); //...do the stuff with the new date...
}


Is there a better way to get the dates?

Answer

You can use the .isAfter and .plusDays to do this over a loop. I would not say better as I haven't done a huge amount of research into the topic but I can confidently say it uses the Java 8 API and is a slight alternative.

LocalDate startDate = LocalDate.now();
LocalDate endDate = startDate.plusMonths(1);
while (!startDate.isAfter(endDate)) {
 System.out.println(startDate);
 startDate = startDate.plusDays(1);
}

Output

2016-07-05
2016-07-06
...
2016-08-04
2016-08-05

Example Here