6

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

date1= Jan 1, 2013  // Starting Date

date2= Jan 16,2013  // End Date

然后它将输出

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

依此类推......直到它到达结束日期。

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

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

4

1 回答 1

31

您应该尝试使用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. 您可以通过创建第二个日历来纠正此问题,lastDate并从中减去一天......

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

2018java.time更新

时光荏苒,事情在变好。Java 8 引入了新的java.timeAPI,它取代了“日期”类,应该优先使用它

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);
}
于 2013-05-28T07:04:37.167 回答