Home > Java > javaTutorial > How to Retrieve a Date Range in Java?

How to Retrieve a Date Range in Java?

Mary-Kate Olsen
Release: 2024-12-13 13:18:14
Original
950 people have browsed it

How to Retrieve a Date Range in Java?

Retrieving a Date Range in Java

One may encounter a situation where a list of dates between two specified dates is required. This range can include both the start and end dates.

Java 8 java.time Package

If using Java 8, the Java Time package provides an elegant solution based on the Joda-Time API:

  1. Declare the start and end dates as LocalDate objects.
  2. Initialize an ArrayList totalDates to store the resulting dates.
  3. Use a while loop to increment the startDate by one day and add it to totalDates.
  4. The loop continues until the startDate exceeds the endDate.

Example:

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

The above is the detailed content of How to Retrieve a Date 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template