You should try Calendar , which will allow you to move 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()); }
Update
This example will contain toDate . You can fix this by creating a second calendar that acts like lastDate and subtracts the 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 array list
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, everything improves. Java 8 introduces a new java.time API that has replaced 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;
source share