将起始日期和结束日期分割为每个月的起始日期和结束日期

import java.time.LocalDate;
import java.time.Month;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.List;

public class DateRangeDivider {

    public static List<MonthRange> divideByMonth(LocalDate startDate, LocalDate endDate) {
        List<MonthRange> monthRanges = new ArrayList<>();

        LocalDate currentDate = startDate;

        while (!currentDate.isAfter(endDate)) {
            int year = currentDate.getYear();
            Month month = currentDate.getMonth();

            LocalDate startOfMonth = currentDate.with(TemporalAdjusters.firstDayOfMonth());
            LocalDate endOfMonth = currentDate.with(TemporalAdjusters.lastDayOfMonth());

            if (endOfMonth.isAfter(endDate)) {
                endOfMonth = endDate;
            }

            MonthRange monthRange = new MonthRange(startOfMonth, endOfMonth);
            monthRanges.add(monthRange);

            currentDate = endOfMonth.plusDays(1);
        }

        return monthRanges;
    }

    public static void main(String[] args) {
        LocalDate startDate = LocalDate.of(2023, Month.JULY, 10);
        LocalDate endDate = LocalDate.of(2023, Month.AUGUST, 9);

        List<MonthRange> dividedMonths = divideByMonth(startDate, endDate);

        for (MonthRange monthRange : dividedMonths) {
            System.out.println("Start Date: " + monthRange.getStart() + ", End Date: " + monthRange.getEnd());
        }
    }
}

class MonthRange {
    private LocalDate start;
    private LocalDate end;

    public MonthRange(LocalDate start, LocalDate end) {
        this.start = start;
        this.end = end;
    }

    public LocalDate getStart() {
        return start;
    }

    public LocalDate getEnd() {
        return end;
    }
}


你可能感兴趣的:(java)