Skip to content

Instantly share code, notes, and snippets.

@MBtech
Created January 12, 2016 13:30
Show Gist options
  • Save MBtech/3fedd2d46e7374fc2a6d to your computer and use it in GitHub Desktop.
Save MBtech/3fedd2d46e7374fc2a6d to your computer and use it in GitHub Desktop.
Loop over dates
//Taken from the stack overflow question
//http://stackoverflow.com/questions/4534924/how-to-iterate-through-range-of-dates-in-java
//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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment