我正在使用JDateChooser
我正在制作一个程序,输出所选日期之间的日期列表。例如:
date1= Jan 1, 2013 // Starting Date
date2= Jan 16,2013 // End Date
然后就会输出
Jan 2, 2013...
Jan 3, 2013..
Jan 4, 2013..
依此类推...直到到达结束日期。
我已经完成了我的程序,一旦您单击 JDatechooser
上的日期,我的程序就完成了。它会自动输出结束日期。 (所选日期 + 15 天 = 结束日期)
我下载了JCalendar
或JDateChooser
这里: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
。您可以通过创建第二个日历作为 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());
}
2018 java.time
更新
时间在流逝,一切都在进步。 Java 8 引入了新的 java.time
API,它取代了“date”类,并且应该优先使用它
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);
}
关于java - 获取两个日期之间的日期列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16785643/