Java 获取指定范围内的日期时间

一、代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public class DateUtils {
    public static void main(String[] args) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String beginTime = "2021-11-25";
        String endTime = "2021-12-02";
        Date beginDate = sdf.parse(beginTime);
        Date endDate = sdf.parse(endTime);
 
        List<Date> dateList = getDateByTimeRange(beginDate, endDate);
        // 输出打印
        dateList.stream().map((item)->sdf.format(item)).forEach(System.out::println);
    }
 
    public static List<Date> getDateByTimeRange(Date beginDate, Date endDate) {
        List dateList = new ArrayList();
        dateList.add(beginDate);
        Calendar beginCalendar = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        beginCalendar.setTime(beginDate);
        Calendar endCalendar = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        endCalendar.setTime(endDate);
        // 测试此日期是否在指定日期之后
        while (endDate.after(beginCalendar.getTime())) {
            // 根据日历的规则,为给定的日历字段添加或减去指定的时间量
            beginCalendar.add(Calendar.DAY_OF_MONTH, 1);
            dateList.add(beginCalendar.getTime());
        }
        return dateList;
    }
}

二、测试结果

 

 

posted @   变体精灵  阅读(1958)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
历史上的今天:
2020-12-02 Linux 安装 Nginx
2020-12-02 Nginx 入门
2020-12-02 Linux rz / sz 命令
点击右上角即可分享
微信分享提示