1

I'm working on a method that can add dates like this :

public static ArrayList<Calendar> addDaysBetween(Calendar day1, Calendar day2)

Which returns the ArrayList containing all the dates between d1 & d2.

So, first I needed to know how many days exists between those two dates (Followed this example : https://stackoverflow.com/a/28865648/4944071)

I wrote something like this :

ArrayList<Calendar> fullDates = new ArrayList<Calendar>();
    if(daysBetween > 0){
        for(int day = 1; day <= daysBetween; day ++){
        Calendar aNewDay = new GregorianCalendar(day1.YEAR, day1.MONTH, day1.DAY_OF_MONTH + day);
        fullDates.add(aNewDay);
        }
     }

But, I'm pretty sure that this will not work at all. Imagine those parameters :

2012/12/21 to 2013/02/14

Not the same year, not the same month, It can't work properly. So, I scratched my head a little bit and decided to use the variable DAY_OF_YEAR.

But, i'm still stuck because I don't know how I could manipulate this variable to create correct dates with good Months & good Years..

Community
  • 1
  • 1
pleguen
  • 63
  • 10

3 Answers3

2

You can try this

    Calendar tmp = (Calendar) day1.clone();
    ArrayList<Calendar> fullDates = new ArrayList<Calendar>();
    while (tmp.before(day2)) {
        fullDates.add((Calendar) tmp.clone());
        tmp.add(Calendar.DAY_OF_MONTH, 1);
    }
    return fullDates;
Liem Do
  • 933
  • 1
  • 7
  • 13
  • 1
    This could cause an infinite loop if `day1` and `day2` have different time (hours, minutes, etc.) or if `day2` < `day1`. Better use `while (tmp.before(day2))` – tobias_k Jun 12 '15 at 09:54
1

With the java8 date api:

    List<LocalDate> listOfDates = new ArrayList<>();
    LocalDate endDay = LocalDate.of(2014, Month.JUNE, 20);
    LocalDate startDay = LocalDate.of(2014, Month.JUNE, 11);

    long days = ChronoUnit.DAYS.between(startDay, endDay);
    for (int i = 1; i <= days; i++) {
        listOfDates.add(startDay.plusDays(i));
    }

if you want to convert to java.util.Date or Calendar:

Date d = Date.from(startDay.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
Calendar cal = Calendar.getInstance();
cal.setTime(d);
griFlo
  • 2,084
  • 18
  • 28
0

Try something like:

currentDay = day1;
while (currentDay < day2){
   addcurrentday to collection
   currentday++
}
bwright
  • 896
  • 11
  • 29