Java Get List of All Days Between Two LocalDateTime
Tags: Java LocalDateTime Java 8 DateUtil
In this Java tutorial, we learn how to write Java utility method to get the all days between two LocalDateTime values and return it a as a List of LocalDateTime objects in Java programming language.
How to get list of all days between two LocalDateTime objects
In this first step, we create a new Java class named DateUtil, and implement a static method named getAllLocalDateTimeBetween(LocalDateTime start, LocalDateTime end) to return a List of LocalDateTime contain the days between start and end as the following Java code.
DateUtil.java
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
public class DateUtil {
/**
* Get list of all days between two LocalDateTime objects and return a List of LocalDateTime
* @param start the start LocalDateTime value
* @param end the end LocalDateTime value
* @return the list of LocalDateTime of all days between start and end
*/
public static List<LocalDateTime> getAllLocalDateTimeBetween(LocalDateTime start, LocalDateTime end) {
List<LocalDateTime> result = new ArrayList<>();
LocalDate startLocalDate = start.toLocalDate();
LocalDate endLocalDate = end.toLocalDate();
while(startLocalDate.isBefore(endLocalDate)) {
result.add(startLocalDate.atStartOfDay());
startLocalDate = startLocalDate.plusDays(1);
}
result.add(endLocalDate.atStartOfDay());
return result;
}
}
In the following example Java program, we show how to use the DateUtil above to get list of all days between two LocalDateTime from 1 August 2022 to 5 August 2022 and print out the result.
GetAllDaysBetweenLocalDateTimeExample.java
import java.time.LocalDateTime;
import java.util.List;
public class GetAllDaysBetweenLocalDateTimeExample {
public static void main(String... args) {
LocalDateTime start = LocalDateTime.parse("2022-08-01T08:29:50.00");
LocalDateTime end = LocalDateTime.parse("2022-08-05T13:30:40.00");
// Get List of All Days Between Two LocalDateTime object
List<LocalDateTime> listOfAllDays = DateUtil.getAllLocalDateTimeBetween(start, end);
listOfAllDays.forEach(System.out::println);
}
}
2022-08-01T00:00
2022-08-02T00:00
2022-08-03T00:00
2022-08-04T00:00
2022-08-05T00:00
Happy Coding 😊
Related Articles
Java Get List of All Date Between Two Date
Java Get List of All Days Between Two Calendar
Java Get List of All LocalDate Between Two LocalDate