按月切割日期

该代码展示了如何使用Java的Calendar,SimpleDateFormat和YearMonth类,将给定的起止日期(如2022-07-15到2023-11-11)按月份切割,获取每个月的开始和结束日期。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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();
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值