Home >Java >javaTutorial >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); } } }
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
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!