Java获取两个时间之间的所有时间集合

取两个时间之间的所有时间集合

比如2021/12/01 14:01——2021/12/01 15:01

public class Test {
    public static List<String> getDate(String startTime, String endTime){
    //定义时间格式
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        List<String> list = new ArrayList<>();
        try {
            // 转化成日期类型
            Date startDate = simpleDateFormat.parse(startTime);
            Date endDate = simpleDateFormat.parse(endTime);

            //用Calendar 进行日期比较判断
            Calendar calendar = Calendar.getInstance();
            while (startDate.getTime()<=endDate.getTime()){
                // 把日期添加到集合
                list.add(simpleDateFormat.format(startDate));
                // 设置日期
                calendar.setTime(startDate);
                //把日期增加一分
                calendar.add(Calendar.MINUTE, 1);
                // 获取增加后的日期
                startDate=calendar.getTime();
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return list;
    }

    public static void main(String[] args) {
        List<String> betweenDate = getDate("2021-12-01 14:01", "2021-12-02 15:01");
        System.out.println(betweenDate);
    }
}

在这里插入图片描述

如果是14:01——15:01之间的时间,修改SimpleDateFormat中的时间格式即可

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");

时间间隔为分钟或者小时或者天数只需修改calendar.add(Calendar.MINUTE, 1)中的参数Date、HOUR即可

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值