最近遇到一个棘手的问题
前端传过来两个String类型的日期值
需要后台循环得到每一天的数据,没数据的赋为0
坑爹的是库里面数据不一定每天都有
于是便有了下面的操作👇👇👇👇
//循环输出时间
public static void main(String[] args) throws ParseException {
String start = "2021-07-01";
String end = "2021-07-02";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date dBegin = sdf.parse(start);
Date dEnd = sdf.parse(end);
List<Date> lDate = findDates(dBegin, dEnd);
for (Date date : lDate) {
System.out.println(sdf.format(date));
}
}
public static List<Date> findDates(Date dBegin, Date dEnd) {
List lDate = new ArrayList();
lDate.add(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);
lDate.add(calBegin.getTime());
}
return lDate;
}