0

How can a range of dates be obtained if two end dates are known?

I.E. If I want all dates between 2015-06-07 00:00:00 and 2015-01-01 00:00:00, how can I do this if both dates have already been made into Date or Timestamp objects?

I know this is possible in Python, using the datetime module:

[str(end_date + timedelta(days=x)) for x in range((start_date-end_date).days + 1)]

What is the equivalent in Java?

ylun.ca
  • 2,504
  • 7
  • 26
  • 47
  • 1
    See http://stackoverflow.com/questions/4534924/how-to-iterate-through-range-of-dates-in-java. – M A Jun 30 '15 at 22:11

2 Answers2

2

Using Joda:

LocalDate from = new LocalDate(fromDate);
LocalDate to = new LocalDate(toDate);
int nDays = Days.daysBetween(from, to).getDays();

List<Date> days = new ArrayList<>(nDays);
for(int i = 0 ; i <= nDays ; i++) {
    days.add(from.plusDays(i).toDate());
}

Or in Java 8:

final LocalDate from = new LocalDate(fromDate);
final LocalDate to = new LocalDate(toDate);
List<Date> days = IntStream.range(0, Days.daysBetween(from, to).getDays() + 1)
                           .map(i -> from.plusDays(i).toDate())
                           .collect(Collectors.toList());
Jean Logeart
  • 52,687
  • 11
  • 83
  • 118
1

java.util.Calendar approach:

Calendar start = Calendar.getInstance();
start.setTime(startDate);
Calendar end = Calendar.getInstance();
end.setTime(endDate);

for (Date date = start.getTime(); start.before(end); start.add(Calendar.DATE, 1), date = start.getTime()) {
    System.out.println(date);
}

java.time.LocalDate approach (requires Java 8):

LocalDate start = startDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
LocalDate end = endDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

for (LocalDate date = start; date.isBefore(end); date = date.plusDays(1)) {
    System.out.println(date);
}
romants
  • 3,660
  • 1
  • 21
  • 33