How to iterate through range of Dates in Java?
Well, you could do something like this using Java 8's time-API, for this problem specifically java.time.LocalDate
(or the equivalent Joda Time classes for Java 7 and older)
for (LocalDate date = startDate; date.isBefore(endDate); date = date.plusDays(1))
{
...
}
I would thoroughly recommend using java.time
(or Joda Time) over the built-in Date
/Calendar
classes.
JodaTime is nice, however, for the sake of completeness and/or if you prefer API-provided facilities, here are the standard API approaches.
When starting off with java.util.Date
instances like below:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date startDate = formatter.parse("2010-12-20");
Date endDate = formatter.parse("2010-12-26");
Here's the legacy java.util.Calendar
approach in case you aren't on Java8 yet:
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()) {
// Do your job here with `date`.
System.out.println(date);
}
And here's Java8's java.time.LocalDate
approach, basically exactly the JodaTime approach:
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)) {
// Do your job here with `date`.
System.out.println(date);
}
If you'd like to iterate inclusive the end date, then use !start.after(end)
and !date.isAfter(end)
respectively.