Java Get List of All Days Between Two OffsetDateTime

Tags: Java OffsetDateTime Java 8 DateUtil

In this Java tutorial, we learn how to write Java utility class to get all days between two OffsetDateTime objects and return it as a List of OffsetDateTime values in Java programming language.

How to get list of all days between two OffsetDateTime objects

Firstly, create a new Java class named DateUtil, and implement a static method getAllDaysBetween(OffsetDateTime start, OffsetDateTime end) which return a List of OffsetDateTime for all days between start and end.

DateUtil.java

import java.time.LocalDate;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.util.ArrayList;
import java.util.List;

public class DateUtil {

    /**
     * The method to get all days between two OffsetDateTime values and return as a List of OffsetDateTime
     * @param start the start OffsetDateTime object
     * @param end the end OffsetDateTime object
     * @return the list of all OffsetDateTime between start and end
     */
    public static List<OffsetDateTime> getAllDaysBetween(OffsetDateTime start, OffsetDateTime end) {
        List<OffsetDateTime> result = new ArrayList<>();
        LocalDate startLocalDate = start.toLocalDate();
        LocalDate endLocalDate = end.toLocalDate();
        while(startLocalDate.isBefore(endLocalDate)) {
            result.add(OffsetDateTime.of(startLocalDate, LocalTime.MIDNIGHT, start.getOffset()));
            startLocalDate = startLocalDate.plusDays(1);
        }

        result.add(OffsetDateTime.of(startLocalDate, LocalTime.MIDNIGHT, start.getOffset()));
        return result;
    }
}

In the following Java program, we show how to use the above DateUtil class to get list of all days between two OffsetDateTime 1 August 2022 to 10 August 2022 and print out the result.

GetAllDaysBetweenOffsetDateTimeExample.java

import java.time.OffsetDateTime;
import java.util.List;

public class GetAllDaysBetweenOffsetDateTimeExample {
    public static void main(String... args) {
        OffsetDateTime start = OffsetDateTime.parse("2022-08-01T07:50:00.00+07:00");
        OffsetDateTime end = OffsetDateTime.parse("2022-08-10T16:50:00.00+07:00");

        // Get List of All Days Between Two OffsetDateTime objects
        List<OffsetDateTime> allDaysBetween = DateUtil.getAllDaysBetween(start, end);

        allDaysBetween.forEach(System.out::println);
    }
}
The output as below.
2022-08-01T00:00+07:00
2022-08-02T00:00+07:00
2022-08-03T00:00+07:00
2022-08-04T00:00+07:00
2022-08-05T00:00+07:00
2022-08-06T00:00+07:00
2022-08-07T00:00+07:00
2022-08-08T00:00+07:00
2022-08-09T00:00+07:00
2022-08-10T00:00+07:00

Happy Coding 😊

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

Java Get List of All Days Between Two LocalDateTime

Java Get List of All Days Between Two ZonedDateTime