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