Search code examples
javajava-time

Getting the YearMonth values between two LocalDate


I have two LocalDate values. Say:

LocalDate startDate = LocalDate.of(2020, 1, 1);
LocalDate endDate =  LocalDate.of(2024, 1, 31);

I need to determine the actual month values (in a List, for example) that are entirely or partially within this date range. I am struggling to find a succinct way to do this.

A List of java.time.YearMonth would work, but so would a list of Strings.

All similar questions I have seen only address the number of months in between the dates, and not getting the actual month values themselves.


Solution

  • It's a simple loop:

    List<YearMonth> months = new ArrayList<>();
    for (var date = startDate; !date.isAfter(endDate); date = date.plusMonths(1)) {
        months.add(YearMonth.from(date));
    }