Get a list of dates between two dates

I use JDateChooser and I create a program that lists the dates between the selected dates. eg:

 date1= Jan 1, 2013 // Starting Date date2= Jan 16,2013 // End Date 

then he will output

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

etc. until it reaches the end date.

I have already finished work on my program, after you click the date on JDateChooser , it will automatically display the end date. (selected date + 15 days = end dates)

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

+4
source share
1 answer

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; //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); } 
+28
source

All Articles