获取区间内每月的第一天和最后一天

1.统计区间内所有的月份

public static List<String> getMonthsBetween(String startMonth, String endMonth) {
        // 定义日期时间格式化器,用于将字符串解析为 YearMonth 对象
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
        // 将开始月份字符串解析为 YearMonth 对象
        YearMonth start = YearMonth.parse(startMonth, formatter);
        // 将结束月份字符串解析为 YearMonth 对象
        YearMonth end = YearMonth.parse(endMonth, formatter);

        // 用于存储中间所有月份的列表
        List<String> months = new ArrayList<>();
        // 从开始月份开始,逐个增加月份,直到达到结束月份
        for (YearMonth month = start;!month.isAfter(end); month = month.plusMonths(1)) {
            // 将当前月份格式化为字符串并添加到列表中
            months.add(month.format(formatter));
        }
        return months;
    }

2.获取每个月份的第一天和最后一天

MonthRangeStrings是个类,内有两个字符串类型的字段  startDateStr, endDateStr

 public static MonthRangeStrings getMonthDateRangeAsString(String monthStr) {
        // 定义解析输入月份字符串的格式化器
        DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM");
        // 定义输出日期字符串的格式化器
        DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        // 将输入的月份字符串解析为 YearMonth 对象
        YearMonth yearMonth = YearMonth.parse(monthStr, inputFormatter);
        // 获取该月的第一天
        LocalDate startDate = yearMonth.atDay(1);
        // 获取该月的最后一天
        LocalDate endDate = yearMonth.atEndOfMonth();

        // 将开始日期和结束日期格式化为字符串
        String startDateStr = startDate.format(outputFormatter);
        String endDateStr = endDate.format(outputFormatter);

        return new MonthRangeStrings(startDateStr, endDateStr);
    }

3.测试

public static void main(String[] args) {
        String startMonth = "2024-01";
        String endMonth = "2025-01";
        // 调用 getMonthsBetween 方法获取中间所有月份
        List<String> months = getMonthsBetween(startMonth, endMonth);
        // 遍历并打印中间所有月份
        for (String month : months) {
            System.out.println("month = " + month);
            //获取第一天和最后一天
            MonthRangeStrings monthDateRangeAsString = getMonthDateRangeAsString(month);
            System.out.println(monthDateRangeAsString.getStartDateStr());
            System.out.println(monthDateRangeAsString.getEndDateStr());
            System.out.println("------------------------");
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值