java获取两个时间内的每一天时间
public static List findDaysStr(String startTime, String endTime) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date dBegin = null;
Date dEnd = null;
try {
dBegin = sdf.parse(startTime);
dEnd = sdf.parse(endTime);
} catch (ParseException e) {
e.printStackTrace();
}
List daysStrList = new ArrayList();
daysStrList.add(sdf.format(dBegin));
Calendar calBegin = Calendar.getInstance();
calBegin.setTime(dBegin);
Calendar calEnd = Calendar.getInstance();
calEnd.setTime(dEnd);
while (dEnd.after(calBegin.getTime())) {
calBegin.add(Calendar.DAY_OF_MONTH, 1);
String dayStr = sdf.format(calBegin.getTime());
daysStrList.add(dayStr);
}
return daysStrList;
}
测试代码
public static void main(String[] args) {
List daysStr = findDaysStr("2022-03-10", "2022-03-15");
System.out.println("daysStr = " + daysStr);
}
结果
daysStr = [2022-03-10, 2022-03-11, 2022-03-12, 2022-03-13, 2022-03-14, 2022-03-15]