Java Get List of All Date Between Two Date
In this Java core tutorial, we learn how to get all days between two Date objects and return result as a List of Date objects in Java programming language.
How to get all days between two Date objects in Java
Firstly, we create a new Java utility class named TimeUtil, and implement the method named getDatesBetween(Date start, Date end), in this method we populate the list of Date values without time between start and end arguments and then return it as List of Date object as the following Java code.
TimeUtil.java
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
public class TimeUtil {
/**
* Get a List of all Dates between two Date objects
* @param start the start Date object
* @param end the end Date object
* @return the List of all Dates between two Date objects
*/
public static List<Date> getAllDatesBetween(Date start, Date end) {
List<Date> result = new ArrayList<>();
Calendar startCalendar = convertDateToCalendarWithoutTime(start);
Calendar endCalendar = convertDateToCalendarWithoutTime(end);
while (startCalendar.before(endCalendar)) {
Date date = startCalendar.getTime();
result.add(date);
startCalendar.add(Calendar.DATE, 1);
}
result.add(endCalendar.getTime());
return result;
}
/**
* Convert a Date object to Calendar object without time
* @param date the Date object
* @return the Calendar object without time
*/
public static Calendar convertDateToCalendarWithoutTime(Date date) {
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.HOUR_OF_DAY, 0);
return calendar;
}
}
In this following Java program, we show how to use the above TimeUtil class to get all days as list of Date object between 1 August 2022 and 5 August 2022.
GetAllDatesBetweenDatesExample.java
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
public class GetAllDatesBetweenDatesExample {
public static void main(String... args) throws ParseException {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date startDate = simpleDateFormat.parse("2022/08/01 08:30:00");
Date endDate = simpleDateFormat.parse("2022/08/05 08:30:00");
// Get List of Date Between Two Date objects
List<Date> listOfDates = TimeUtil.getAllDatesBetween(startDate, endDate);
listOfDates.forEach(System.out::println);
}
}
Mon Aug 01 00:00:00 ICT 2022
Tue Aug 02 00:00:00 ICT 2022
Wed Aug 03 00:00:00 ICT 2022
Thu Aug 04 00:00:00 ICT 2022
Fri Aug 05 00:00:00 ICT 2022
Happy Coding 😊
Related Articles
Java Get List of All LocalDate Between Two LocalDate
Java Get List of All Days Between Two LocalDateTime
Java Get List of All Days Between Two OffsetDateTime
Java Get List of All Days Between Two ZonedDateTime