user3288346 user3288346 - 22 days ago 5
Java Question

How to build a list of LocalDate from a given range?

I have the following method, where I have the

startDate
and the
endDate
of type String
yyyy/mm/dd
. I want to return a
List<LocalDate>


protected List<LocalDate> getDateList(String startDate, String endDate) {

//build list here

}


How can I do this in Java 8?

Answer

Assuming that your input data is correct, we could use a Stream API to generate all dates in the given range:

final LocalDate start = LocalDate.parse(startDate, DateTimeFormatter.ofPattern("yyyy/MM/dd"));
final LocalDate end = LocalDate.parse(endDate, DateTimeFormatter.ofPattern("yyyy/MM/dd"));

final int days = (int) start.until(end, ChronoUnit.DAYS);

return Stream.iterate(start, d -> d.plusDays(1))
  .limit(days)
  .collect(Collectors.toList());

Example:

getDateList("2012/10/10", "2012/10/12")

[2012-10-10, 2012-10-11]

If you want to include the ending date, you need to use .limit(days + 1).