Get the list of dates between two dates

Maguzu picture Maguzu · May 28, 2013 · Viewed 17.8k times · Source

I'm using JDateChooser and I'm making a program that output the list of dates between the selected dates. for example:

date1= Jan 1, 2013  // Starting Date

date2= Jan 16,2013  // End Date

then it will output

Jan 2, 2013...
Jan 3, 2013.. 
Jan 4, 2013..

and so on... until it reaches the end date.

I already finish working on the my program that once you click a date on the JDatechooser it will output the end date automatically. (selected date + 15 days = end dates)

I download the JCalendar or JDateChooser here: http://www.toedter.com/en/jcalendar/

Answer

MadProgrammer picture MadProgrammer · May 28, 2013

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);
}