1

I'm trying to create a list of dates that are included between two dates. Here is how I tried to do it :

public void fillDates() {
        long diffInMillis = Math.abs(secondDate.getTime() - firstDate.getTime());
        long diff = TimeUnit.DAYS.convert(diffInMillis, TimeUnit.MILLISECONDS);

        for (int i=0; i <= diff; i++) {
            Calendar calendar = Calendar.getInstance();
            calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.DAY_OF_MONTH), calendar.get(Calendar.DAY_OF_MONTH)+i);
            Long date = calendar.getTime().getTime();
            String str = convertDate(date);
            dates.add(str);
        }
    }

dates is a list of strings, and convertDate() is converting a long date into a string date. But I think the problem comes from the lines above, as the same day is added to the list every time.

I know other similar questions exists, but I didn't find any that really helped me... But if you have an entirely different solution for me, don't hesitate ! I'm just trying to get a list of (string) dates between two dates that are submitted by the user through Date Pickers.

LoneRetriever
  • 119
  • 10

1 Answers1

1

You should not be using Calendar, Date or SmipleDateFormat. They're troublesome. You are better off using classes from the java.time package.

If both firstDate and secondDate are LocalDates, then it'll become much easier:

List<String> dateStrings = firstDate.datesUntil(secondDate.plusDays(1))
    .map(date -> date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")))
    .collect(Collectors.toList());

Note that datesUntil exists since Java 9. For Java 8, this is a helper method instead:

public static Stream<LocalDate> datesUntil(LocalDate from, LocalDate toExclusive) {
    long daysBetween = ChronoUnit.DAYS.between(from, toExclusive);
    return Stream.iterate(from, t -> t.plusDays(1))
        .limit(daysBetween);
    }
MC Emperor
  • 22,334
  • 15
  • 80
  • 130