Search code examples
javadateiteration

How to iterate through range of Dates in Java?


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.


Solution

  • 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.