How to calculate the difference in months between two dates in Java?

In Java, you can use the Period class from the java.time package to calculate the difference between two dates. Below is an example code demonstrating how to calculate the difference in months between two dates.

import java.time.LocalDate;
import java.time.Period;

public class DateDifference {

    public static void main(String[] args) {
        LocalDate date1 = LocalDate.of(2021, 9, 1);
        LocalDate date2 = LocalDate.of(2022, 4, 1);

        Period period = Period.between(date1, date2);
        int months = period.getMonths();

        System.out.println("相差的月份: " + months);
    }
}

In the example above, we created two date objects, date1 and date2, using the LocalDate class. We then used the Period.between() method to calculate the difference between the two dates and stored the result in the period object. Finally, we used the getMonths() method to retrieve the difference in months and printed it out.

Please note that the getMonths() method of the Period class returns the difference in months between two dates, not the absolute value. If the first date is after the second date, the result will be negative. If you need to obtain the absolute difference in months, you can use the Math.abs() method.

bannerAds