Get the list of dates between two dates [closed]

寵の児 提交于 2019-11-27 16:13:12

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);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!