栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

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

public class Test {
    public static List getDate(String startTime, String endTime){
    //定义时间格式
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        List 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 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即可

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/677349.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号