How to iterate through range of Dates in Java?

user531743 picture user531743 · Dec 26, 2010 · Viewed 125k times · Source

In my script I need to perform a set of actions through range of dates, given a start and end date.
Please provide me guidance to achieve this using Java.

for ( currentDate = starDate; currentDate < endDate; currentDate++) {

}

I know the above code is simply impossible, but I do it in order to show you what I'd like to achieve.

Answer

Jon Skeet picture Jon Skeet · Dec 26, 2010

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.