Java — Get the list of dates between two dates | Code Factory

package com.example.java.programming.datetime;import java.time.LocalDate;
import java.util.Calendar;
import java.util.Date;
/**
* @author code.factory
*
*/
public class Test {
public static void main(String... args) {
// Java <= 7
Date fromDate = new Date(2020, 06, 15);
Date toDate = new Date(2020, 06, 20);
Calendar cal = Calendar.getInstance();
cal.setTime(fromDate);
while (cal.getTime().before(toDate)) {
cal.add(Calendar.DATE, 1);
System.out.println(cal.getTime());
}
System.out.println();

// Java <= 7
Calendar lastDate = Calendar.getInstance();
lastDate.setTime(toDate);
lastDate.add(Calendar.DATE, -1);
Calendar cal2 = Calendar.getInstance();
cal2.setTime(fromDate);
while (cal2.before(lastDate)) {
cal2.add(Calendar.DATE, 1);
System.out.println(cal2.getTime());
}
System.out.println();

// Java 8+
LocalDate firstDate = LocalDate.of(2020, 06, 15);
LocalDate secondDate = LocalDate.of(2020, 06, 20);
LocalDate current = firstDate;
//current = current.plusDays(1); // If you don't want to include the start date
//toDate = toDate.plusDays(1); // If you want to include the end date
while (current.isBefore(secondDate)) {
System.out.println(current);
current = current.plusDays(1);
}
}
}
Fri Jul 16 00:00:00 IST 3920
Sat Jul 17 00:00:00 IST 3920
Sun Jul 18 00:00:00 IST 3920
Mon Jul 19 00:00:00 IST 3920
Tue Jul 20 00:00:00 IST 3920
Fri Jul 16 00:00:00 IST 3920
Sat Jul 17 00:00:00 IST 3920
Sun Jul 18 00:00:00 IST 3920
Mon Jul 19 00:00:00 IST 3920
2020-06-15
2020-06-16
2020-06-17
2020-06-18
2020-06-19

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store