Java8 给定时间范围生成周期

1 给定时间范围获取月周期 

获取指定时间所在月的第一天/最后一天见上期工具类(Java8时间工具类_污鸦嘴的博客-CSDN博客)

public class DateTest {

    public static void main(String[] args) {

        List<TaskCycle> taskCycles = new ArrayList<>();

        LocalDateTime start = LocalDateTime.of(2022, 7, 1, 0, 0, 0);
        LocalDateTime end = LocalDateTime.of(2022, 10, 15, 0, 0, 0);
        int index = 1;

        while (start.isBefore(end)) {
            TaskCycle taskCycle = new TaskCycle(index, DateTimeUtils.getFirstDayOfMonth(start), DateTimeUtils.getLastDayOfMonth(start),
                    start.format(DateTimeFormatter.ofPattern("yyyy-MM")));
            taskCycles.add(taskCycle);

            index++;
            start = start.plusMonths(1);
        }
        
        taskCycles.forEach(System.out::println);

    }

    @Data
    @AllArgsConstructor
    static class TaskCycle {
        private int index;
        private LocalDateTime start;
        private LocalDateTime end;
        private String month;
    }

}

结果如下 

DateTest.TaskCycle(index=1, start=2022-07-01T00:00, end=2022-07-31T23:59:59, month=2022-07)
DateTest.TaskCycle(index=2, start=2022-08-01T00:00, end=2022-08-31T23:59:59, month=2022-08)
DateTest.TaskCycle(index=3, start=2022-09-01T00:00, end=2022-09-30T23:59:59, month=2022-09)
DateTest.TaskCycle(index=4, start=2022-10-01T00:00, end=2022-10-31T23:59:59, month=2022-10)

2 根据指定时间段及指定频率获取周期

public class DateTest {

    public static void main(String[] args) {

        List<TaskCycle> taskCycles = new ArrayList<>();

        LocalDateTime start = LocalDateTime.of(2022, 7, 1, 0, 0, 0);
        LocalDateTime end = LocalDateTime.of(2022, 8, 31, 0, 0, 0);
        int time = 7;
        int index = 0;

        start.plusDays(time).minusSeconds(1);
        LocalDateTime startTime = start;
        LocalDateTime endTime = start.plusDays(time).minusSeconds(1);
        taskCycles.add(new TaskCycle(index, startTime, endTime));

        while (endTime.isBefore(end)) {
            startTime = endTime.plusSeconds(1);
            endTime = startTime.plusDays(time).minusSeconds(1);
            index++;
            taskCycles.add(new TaskCycle(index, startTime, endTime));
            // 设定最后一周期的结束时间
            if (endTime.isAfter(end)) {
                taskCycles.get(taskCycles.size() - 1).setEnd(end);
            }
        }

        taskCycles.forEach(System.out::println);

    }

    @Data
    @AllArgsConstructor
    static class TaskCycle {
        private int index;
        private LocalDateTime start;
        private LocalDateTime end;
    }

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值