//时间区间补全方法
public static List<String> findDates(String beginTime, String endTime)
throws ParseException {
List<String> allDate = new ArrayList();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date dBegin = sdf.parse(beginTime);
Date dEnd = sdf.parse(endTime);
allDate.add(sdf.format(dBegin));
Calendar calBegin = Calendar.getInstance();
// 使用给定的 Date 设置此 Calendar 的时间
calBegin.setTime(dBegin);
Calendar calEnd = Calendar.getInstance();
// 使用给定的 Date 设置此 Calendar 的时间
calEnd.setTime(dEnd);
// 测试此日期是否在指定日期之后
while (dEnd.after(calBegin.getTime())) {
// 根据日历的规则,为给定的日历字段添加或减去指定的时间量
calBegin.add(Calendar.DAY_OF_MONTH, 1);
allDate.add(sdf.format(calBegin.getTime()));
}
System.out.println("时间==" + allDate);
return allDate;
}
===
//集合中包含2019-05-01/2019-05-05,不需要可去除
List<String> list = new ArrayList<>();
try {
//只有结束时间大于开始时间时才进行查询===改完
list = findDates(beginTime, endTime);
System.out.println("时间啊啊啊==" + list);
} catch (ParseException e) {
e.printStackTrace();
}
本文介绍了一个实用的方法,用于生成指定开始时间和结束时间之间的所有日期。通过使用Java的Calendar类和SimpleDateFormat,该方法能够准确地补全两个日期间的所有日期,适用于各种需要按日期迭代的应用场景。

5359

被折叠的 条评论
为什么被折叠?



