Home > Article > Backend Development > How to List All Months Between Two Dates in Java?
Listing Months Between Two Dates
Determining the months between two specified dates can be a challenging task. To accomplish this, we delve into a Java-centric approach, employing the intuitive Java 8 Date API.
The first step involves parsing the input dates into Java 8 LocalDate objects. We then initialize a Month instance corresponding to the start date.
Next, we iterate through the months until we reach the end date. Within each iteration, we capture the format of the month and year to build the desired list.
Below is a code snippet that comprehensively addresses this task:
<code class="java">import java.time.LocalDate; import java.time.Month; import java.util.ArrayList; import java.util.List; class MonthLister { public static void main(String[] args) { // Parse input dates LocalDate startDate = LocalDate.parse("2010-12-02"); LocalDate endDate = LocalDate.parse("2012-05-06"); // Initialize current month Month currentMonth = startDate.getMonth(); // Create list to store months List<String> months = new ArrayList<>(); // Iterate through months until end date is reached while (!currentMonth.equals(endDate.getMonth())) { // Capture format of month and year months.add(currentMonth.toString() + "-" + startDate.getYear()); // Increment current month startDate = startDate.plusMonths(1); currentMonth = startDate.getMonth(); } // Output list of months months.forEach(System.out::println); } }</code>
In this snippet, the encapsulation of code within the MonthLister class enhances its reusability and maintainability. The main method orchestrates the date parsing, month iteration, and list formation. The output is a neatly formatted list of months between the specified dates.
The above is the detailed content of How to List All Months Between Two Dates in Java?. For more information, please follow other related articles on the PHP Chinese website!