Home > Java > javaTutorial > How to Generate an Array of Dates Between Two Given Dates in Java?

How to Generate an Array of Dates Between Two Given Dates in Java?

Linda Hamilton
Release: 2024-12-18 00:09:10
Original
803 people have browsed it

How to Generate an Array of Dates Between Two Given Dates in Java?

Obtaining an Array of Dates Within a Specified Range in Java

Determining a range of dates between two specified dates is a common programming task. To achieve this, Java offers various approaches, including the java.time package introduced in Java 8.

java.time Package Solution:

For a simpler and more streamlined solution, consider utilizing the java.time package. Here's how to implement it:

import java.time.LocalDate;
import java.time.Period;
import java.util.ArrayList;
import java.util.List;

public class DateRange {

    public static void main(String[] args) {
        String startDateString = "2014-05-01";
        String endDateString = "2014-05-10";

        LocalDate startDate = LocalDate.parse(startDateString);
        LocalDate endDate = LocalDate.parse(endDateString);

        // Calculate the period between the dates
        Period period = Period.between(startDate, endDate);

        // Store the dates in a list
        List<LocalDate> dateList = new ArrayList<>();
        for (int i = 0; i <= period.getDays(); i++) {
            dateList.add(startDate.plusDays(i));
        }

        // Print the date list
        for (LocalDate date : dateList) {
            System.out.println(date);
        }
    }
}
Copy after login

Output:

2014-05-01
2014-05-02
2014-05-03
2014-05-04
2014-05-05
2014-05-06
2014-05-07
2014-05-08
2014-05-09
2014-05-10
Copy after login

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

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