您应该尝试使用Calendar
,这将允许您从一个日期走到另一个日期...
Date fromDate = ...;
Date toDate = ...;
System.out.println("From " + fromDate);
System.out.println("To " + toDate);
Calendar cal = Calendar.getInstance();
cal.setTime(fromDate);
while (cal.getTime().before(toDate)) {
cal.add(Calendar.DATE, 1);
System.out.println(cal.getTime());
}
更新
此示例将包括toDate
. 您可以通过创建第二个日历来纠正此问题,lastDate
并从中减去一天......
Calendar lastDate = Calendar.getInstance();
lastDate.setTime(toDate);
lastDate.add(Calendar.DATE, -1);
Calendar cal = Calendar.getInstance();
cal.setTime(fromDate);
while (cal.before(lastDate)) {...}
这将为您提供开始日期和结束日期“之间”的所有日期。
将日期添加到 ArrayList
List<Date> dates = new ArrayList<Date>(25);
Calendar cal = Calendar.getInstance();
cal.setTime(fromDate);
while (cal.getTime().before(toDate)) {
cal.add(Calendar.DATE, 1);
dates.add(cal.getTime());
}
2018java.time
更新
时光荏苒,事情在变好。Java 8 引入了新的java.time
API,它取代了“日期”类,应该优先使用它
LocalDate fromDate = LocalDate.now();
LocalDate toDate = LocalDate.now();
List<LocalDate> dates = new ArrayList<LocalDate>(25);
LocalDate current = fromDate;
//current = current.plusDays(1); // If you don't want to include the start date
//toDate = toDate.plusDays(1); // If you want to include the end date
while (current.isBefore(toDate)) {
dates.add(current));
current = current.plusDays(1);
}