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

本文介绍了一个Java程序,名为DateRangeDivider,它使用LocalDate类和TemporalAdjusters来将给定的开始日期(2023年7月10日)到结束日期(2023年8月9日)分割成一系列月份范围,并打印每个范围的起始和结束日期。
摘要由CSDN通过智能技术生成
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;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值