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