How to Get All Dates Between Two Dates?

1. Overview

The new Time API introduced in Java 8 made it possible to process date and time without using external libraries.

In this short tutorial, we will take a look at how getting all dates between two dates become easier over the time in different versions of Java.

2. Using Java 7

In Java 7, One way to calculate it is using Calendar instance, running a loop and adding 1 day in each iteration using add method and Calendar.Date field unit it reaches the end date.

Here is the code demonstrating it – using Calendar instance:

public static List<Date> getDatesBetweenUsingJava7(
  Date startDate, Date endDate) {
    List<Date> datesInRange = new ArrayList<>();
    Calendar calendar = new GregorianCalendar();
    calendar.setTime(startDate);
    
    Calendar endCalendar = new GregorianCalendar();
    endCalendar.setTime(endDate);

    while (calendar.before(endCalendar)) {
        Date result = calendar.getTime();
        datesInRange.add(result);
        calendar.add(Calendar.DATE, 1);
    }
    return datesInRange;
}

3. Using Java 8

In Java 8, we can now create a continuous infinite Stream of dates and take only the relevant part. Unfortunately, there is no way of terminating an infinite Stream when a predicate gets matched – this is why we need to calculate the number of days between those two days and then simply limit() the Stream:

public static List<LocalDate> getDatesBetweenUsingJava8(
  LocalDate startDate, LocalDate endDate) { 
 
    long numOfDaysBetween = ChronoUnit.DAYS.between(startDate, endDate); 
    return IntStream.iterate(0, i -> i + 1)
      .limit(numOfDaysBetween)
      .mapToObj(i -> startDate.plusDays(i))
      .collect(Collectors.toList()); 
}

Notice how, first, we can get the difference of days between two dates using the between function – associated with DAYS constant of ChronoUnit enumeration.

Then we create a Stream of integers representing the number of days since the starting date. In the next step, we convert our integers to LocalDate objects using the plusDays() API.

Finally, we collect everything into a list instance.

4. Using Java 9

Finally, Java 9 brings dedicated methods for calculating this:

public static List<LocalDate> getDatesBetweenUsingJava9(
  LocalDate startDate, LocalDate endDate) {
 
    return startDate.datesUntil(endDate)
      .collect(Collectors.toList());
}

We can get the dates between two dates with single method call using the dedicated datesUntil method of a LocalDate class. The datesUntill returns the sequentially ordered Stream of dates starting from the date object whose method is called to the date given as method argument.

5. Conclusion

In this quick article, we looked at how can we get all dates between two dates using the different versions of Java.

We discussed how Time API introduced in Java 8 release made it easier to run operations over date literals and in Java 9, it can be done by just calling datesUntil.

And, as always, the code snippets can be found over on GitHub.

Related posts:

Inheritance with Jackson
Java Program to Apply DFS to Perform the Topological Sorting of a Directed Acyclic Graph
A Quick Guide to Spring MVC Matrix Variables
Tìm hiểu về xác thực và phân quyền trong ứng dụng
Từ khóa throw và throws trong Java
Guide to Java 8’s Collectors
Java Program to Implement Depth-limited Search
Redirect to Different Pages after Login with Spring Security
Apache Tiles Integration with Spring MVC
Guide to Selenium with JUnit / TestNG
Query Entities by Dates and Times with Spring Data JPA
Java Program to Implement Stack API
Java Program to Implement CopyOnWriteArraySet API
Java Program to Implement Sparse Array
Quick Guide to Spring MVC with Velocity
Java Program to Apply Above-Below-on Test to Find the Position of a Point with respect to a Line
A Guide to Java SynchronousQueue
Abstract class và Interface trong Java
Vấn đề Nhà sản xuất (Producer) – Người tiêu dùng (Consumer) và đồng bộ hóa các luồng trong Java
Java Program to Implement Sorted List
Java Program to Construct an Expression Tree for an Postfix Expression
Java Program to Find the Minimum value of Binary Search Tree
Java Program to Implement Gaussian Elimination Algorithm
Giới thiệu Google Guice – Dependency injection (DI) framework
Send email with SMTPS (eg. Google GMail)
Check if a String is a Palindrome in Java
Java Program to Implement HashTable API
Kết hợp Java Reflection và Java Annotations
Xử lý ngoại lệ đối với trường hợp ghi đè phương thức trong java
Java – InputStream to Reader
Java 8 Streams peek() API
Spring Boot Gradle Plugin