You should try using Calendar, which will allow you to walk from one date to another...
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());
}
Updated
This example will include the toDate
. You can rectify this by creating a second calendar that acts as the lastDate
and subtracting a day from it...
Calendar lastDate = Calendar.getInstance();
lastDate.setTime(toDate);
lastDate.add(Calendar.DATE, -1);
Calendar cal = Calendar.getInstance();
cal.setTime(fromDate);
while (cal.before(lastDate)) {...}
This will give you all the dates "between" the start and end dates, exclusively.
Adding Dates to an 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());
}
2018 java.time
Update
Time moves on, things improve. Java 8 introduces the new java.time
API which has superseded the "date" classes and should, as a preference, be used instead
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);
}