How does Java calculate the difference between two dates by months and days?

for example, 4.1-8.2 is 4 months and 2 days

Feb.28,2021

you can use joda-time to manipulate time conveniently.

</span>

Java8 API getDiff :

static int[] getDiff(LocalDate start, LocalDate end) {
    if (!start.isBefore(end)) {
        throw new IllegalArgumentException("Start must not be before end.");
    }

    Period period = Period.between(start, end);

    int years = period.getYears();
    int months = period.getMonths();
    int days = period.getDays();

    return new int[] {years * 12 + months, days};
}
Menu