import java.time.LocalDate; import java.time.YearMonth; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class DateRangeGenerator { public static void main(String[] args) { String startDateString = "2022-07-15"; String endDateString = "2023-11-11"; LocalDate startDate = LocalDate.parse(startDateString).withDayOfMonth(1); LocalDate endDate = LocalDate.parse(endDateString); Map<LocalDate, LocalDate> dateMap = generateDateRanges(startDate, endDate); System.out.println(dateMap.toString()); for (LocalDate date : dateMap.keySet()) { LocalDate checkStartDateMonth; LocalDate checkEndDateMonth = dateMap.get(date); if (date.equals(startDate)) { checkStartDateMonth = LocalDate.parse(startDateString); } else { checkStartDateMonth = date.withDayOfMonth(1); } System.out.println(checkStartDateMonth); System.out.println(checkEndDateMonth); } } private static Map<LocalDate, LocalDate> generateDateRanges(LocalDate startDate, LocalDate endDate) { Map<LocalDate, LocalDate> dateMap = new HashMap<>(); LocalDate currentDate = startDate; while (!currentDate.isAfter(endDate)) { LocalDate endOfMonth = getEndOfMonth(currentDate); dateMap.put(currentDate, endOfMonth); currentDate = currentDate.plusMonths(1).withDayOfMonth(1); } return dateMap; } private static LocalDate getEndOfMonth(LocalDate date) { YearMonth yearMonth = YearMonth.from(date); return yearMonth.atEndOfMonth(); } }
按月切割日期
于 2023-12-28 15:48:54 首次发布