给出一个时间段,列出该时间段里所有的日期(最小单位:天)
作者:互联网
public class demo11 {
public static void main(String[] args) {
String start = "2020-08-08";
String end = "2021-09-08";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date dStart = null;
Date dEnd = null;
try {
dStart = sdf.parse(start);
dEnd = sdf.parse(end);
} catch (ParseException e) {
e.printStackTrace();
}
List<Date> dateList = findDates(dStart, dEnd);
for (Date date : dateList) {
System.out.println(sdf.format(date));
}
}
//JAVA获取某段时间内的所有日期
public static List<Date> findDates(Date dStart, Date dEnd) {
Calendar cStart = Calendar.getInstance();
cStart.setTime(dStart);
List dateList = new ArrayList();
//别忘了,把起始日期加上
dateList.add(dStart);
// 此日期是否在指定日期之后
while (dEnd.after(cStart.getTime())) {
// 根据日历的规则,为给定的日历字段添加或减去指定的时间量
cStart.add(Calendar.DAY_OF_MONTH, 1);
dateList.add(cStart.getTime());
}
return dateList;
}
}
标签:dStart,dateList,最小,cStart,sdf,时间段,Date,列出,dEnd 来源: https://www.cnblogs.com/rwjnb/p/16130190.html