获取两个日期之间的日期列表

我正在使用JDateChooser ,我正在制作一个程序,输出所选日期之间的日期列表。 例如:

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

然后它会输出

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

等等……直到它到达结束日期。

我已经完成了我的程序,一旦你点击JDatechooser上的日期,它就会自动输出结束日期。 (选定日期+ 15天=结束日期)

我在这里下载JCalendarJDateChooser : http : //www.toedter.com/en/jcalendar/

您应该尝试使用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 。 你可以通过创建第二个日历作为lastDatelastDate减去一天来纠正这个问题……

 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 dates = new ArrayList(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更新

时间继续前进,事情有所改善。 Java 8引入了新的java.time API,它取代了“日期”类,并且应该作为首选使用

 LocalDate fromDate = LocalDate.now(); LocalDate toDate = LocalDate.now(); List dates = new ArrayList(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); }