Search code examples
javadatejava-timelocaldate

Java - create group of dates by Month from 2 dates


Using Java 8

Goal

From two dates (for example: firstDay 2018-09-01 and lastDay 2018-11-10), I would like to create two arrays of firstDay and lastDay created by month. For example:

List<LocalDate> firstDays = [2018-09-01,2018-10-01,2018-11-01]
List<LocalDate> lastDays = [2018-09-30, 2018-10-31,2018-11-10]

Eventually, I would like this method to apply also for years (for example: firstDay 2018-12-10 and lastDay 2019-01-06).

Issue

I don't now what to use to fullfill that goal. I'm still searching. Could you help me please?


Solution

  • In an iterative style, and handling edge cases:

    LocalDate startDate = LocalDate.of(2018, 9, 1);
    LocalDate endDate = LocalDate.of(2018, 11, 10);
    
    List<LocalDate> firstDays = new ArrayList<>();
    List<LocalDate> lastDays = new ArrayList<>();
    
    LocalDate firstOfMonth = startDate.withDayOfMonth(1);
    LocalDate lastOfMonth = startDate.withDayOfMonth(startDate.lengthOfMonth());
    
    while (firstOfMonth.isBefore(endDate)) {
        firstDays.add(firstOfMonth.isBefore(startDate) ? startDate : firstOfMonth);
        lastDays.add(endDate.isBefore(lastOfMonth) ? endDate : lastOfMonth);
    
        firstOfMonth = firstOfMonth.plus(1, ChronoUnit.MONTHS);
        lastOfMonth = firstOfMonth.withDayOfMonth(firstOfMonth.lengthOfMonth());
    }
    
    System.out.println(firstDays);
    System.out.println(lastDays);
    

    Output:

    [2018-09-01, 2018-10-01, 2018-11-01]
    [2018-09-30, 2018-10-31, 2018-11-10]