0

I have 2 dates:

Calendar c1 = Calendar.getInstance();
c1.set(2014, 1, 1);

Calendar c2 = Calendar.getInstance();
c2.set(2013, 11, 1);

How can I get a list of all the valid dates in between (and including) these two dates?

Eduardo
  • 6,900
  • 17
  • 77
  • 121
  • possible duplicate of [Get the list of dates between two dates](http://stackoverflow.com/questions/16785643/get-the-list-of-dates-between-two-dates) – Steve Benett Jul 13 '14 at 15:24
  • possible duplicate of [how to get a list of dates between two dates in java](http://stackoverflow.com/questions/2689379/how-to-get-a-list-of-dates-between-two-dates-in-java) – Basil Bourque Jul 13 '14 at 15:48

4 Answers4

1

Try with Joda-Time

List<LocalDate> dates = new ArrayList<LocalDate>();
int days = Days.daysBetween(startDate, endDate).getDays();
for (int i=0; i < days; i++) {
    LocalDate d = startDate.withFieldAdded(DurationFieldType.days(), i);
    dates.add(d);
}
Rakesh KR
  • 6,357
  • 5
  • 40
  • 55
1

Start by determining which of the two dates is earlier. If c1 comes after c2, swap the objects.

After that make a loop that prints the current date from c1, and then calls c1.add(Calendar.DAY_OF_MONTH, 1). When c1 exceeds c2, end the loop.

Here is a demo on ideone. Note that month numbers are zero-based, so your example enumerates dates between Dec-1, 2013 and Feb-1, 2014, inclusive, and not between Nov-1, 2013 and Jan-1, 2014, as the numbers in the program might suggest.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

I would in general also recommend using joda-time, but here's a pure Java solution:

Calendar c1 = Calendar.getInstance();
c1.set(2013, 1, 1);

Calendar c2 = Calendar.getInstance();
c2.set(2014, 11, 1);

while (!c1.after(c2)) {
    System.out.println(c1.getTime());

    c1.add(Calendar.DAY_OF_YEAR, 1);
}

In essence: keep incrementing the earlier date until it falls after the later date. If you want to keep them in an actual List<Calendar>, you'll need to copy c1 on every iteration and add the copy to the list.

Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156
1

The following functions should do what you want without having to include any other dependencies:

@Nonnull
public static List<Date> getDaysBetween(@Nonnull final Date start, @Nonnull final Date end)
{
    final List<Date> dates = new ArrayList<Date>();
    dates.add(start);
    Date nextDay = dayAfter(start);
    while (nextDay.compareTo(end) <= 0)
    {
        dates.add(nextDay);
    }
    return dates;
}

@Nonnull
public static Date dayAfter(final Date date)
{
    final GregorianCalendar gc = new GregorianCalendar();
    gc.setTime(date);
    gc.roll(Calendar.DAY_OF_YEAR, true);
    return gc.getTime();
}
Community
  • 1
  • 1