Home > Java > javaTutorial > How Can I Retrieve a List of Dates Within a Specific Range in Java?

How Can I Retrieve a List of Dates Within a Specific Range in Java?

DDD
Release: 2024-12-06 06:48:11
Original
852 people have browsed it

How Can I Retrieve a List of Dates Within a Specific Range in Java?

Retrieving Date Ranges in Java

In Java, obtaining a list of dates within a specified range is a common requirement. This task necessitates accounting for all dates, inclusive of the start and end dates.

Java 8

Java 8 introduces the java.time package, which provides a powerful and intuitive solution for date-related operations. To achieve the desired result, use the following code:

String startDate = "2014-05-01";
String endDate = "2014-05-10";
LocalDate start = LocalDate.parse(startDate);
LocalDate end = LocalDate.parse(endDate);
List<LocalDate> dates = new ArrayList<>();

while (!start.isAfter(end)) {
    dates.add(start);
    start = start.plusDays(1);
}
Copy after login

The code parses the start and end dates into LocalDate objects, initializes an empty list, and enters a loop. It iteratively adds the current date to the list and increments the date until it exceeds the end date. This generates a comprehensive list of all dates within the range.

The above is the detailed content of How Can I Retrieve a List of Dates Within a Specific Range 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template