Java Data Type How to - Get list of local dates between two java.util.Date








Question

We would like to know how to get list of local dates between two java.util.Date.

Answer

//from  w w w  .j a va2s.  c  o  m
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class Main {
  public static void main(String[] argv) {
    System.out.println(getDatesInPeriod(new Date(1422312311223L),
        new Date(1462312311223L)));
  }

  public static List<LocalDate> getDatesInPeriod(Date startDate, Date endDate) {
    List<LocalDate> dates = new ArrayList<>();
    LocalDate start = toLocalDate(startDate);
    LocalDate end = toLocalDate(endDate);
    while (!start.equals(end)) {
      dates.add(start);
      start = start.plusDays(1);
    }
    return dates;
  }

  public static LocalDate toLocalDate(Date date) {
    Date lDate = new Date(date.getTime());
    return lDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
  }
}

The code above generates the following result.