How to iterate through range of Dates in Java? How to iterate through range of Dates in Java? java java

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.


Java 8 style, using the java.time classes:

// Monday, February 29 is a leap day in 2016 (otherwise, February only has 28 days)LocalDate start = LocalDate.parse("2016-02-28"),          end   = LocalDate.parse("2016-03-02");// 4 days between (end is inclusive in this example)Stream.iterate(start, date -> date.plusDays(1))        .limit(ChronoUnit.DAYS.between(start, end) + 1)        .forEach(System.out::println);

Output:

2016-02-282016-02-292016-03-012016-03-02

Alternative:

LocalDate next = start.minusDays(1);while ((next = next.plusDays(1)).isBefore(end.plusDays(1))) {    System.out.println(next);}

Java 9 added the datesUntil() method:

start.datesUntil(end.plusDays(1)).forEach(System.out::println);