Home > Java > javaTutorial > How to Generate a List of Dates Between Two Given Dates in Java?

How to Generate a List of Dates Between Two Given Dates in Java?

Patricia Arquette
Release: 2024-12-13 08:27:15
Original
411 people have browsed it

How to Generate a List of Dates Between Two Given Dates in Java?

How to Obtain a List of Dates within a Specified Range in Java

When seeking a method to generate a list of dates falling between two specified dates, the most suitable approach depends on the version of Java you are utilizing. Here are the recommended methods based on the available Java versions:

Java 8 and Above: java.time Package

For Java 8 and subsequent versions, the java.time package provides a comprehensive solution to this task. This package seamlessly integrates the features of the Joda-Time API into Java.

Implementation:

String s = "2014-05-01";
String e = "2014-05-10";
LocalDate start = LocalDate.parse(s);
LocalDate end = LocalDate.parse(e);
List<LocalDate> totalDates = new ArrayList<>();
while (!start.isAfter(end)) {
    totalDates.add(start);
    start = start.plusDays(1);
} 
Copy after login

This code snippet will generate a list of dates from the specified start date (start) to the end date (end), including both the start and end dates. Each date in the resulting list is represented as a LocalDate object.

The above is the detailed content of How to Generate a List of Dates Between Two Given Dates in Java?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template