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