How do I get number of months between two dates in Joda?

The code below show you how to use the Months class to calculate the different in months between two dates.

package org.kodejava.example.joda;

import org.joda.time.DateMidnight;
import org.joda.time.Months;

import java.util.Date;

public class MonthsBetweenDemo {
    public static void main(String[] args) {
        //
        // Creates an instance of start and end dates.
        //
        DateMidnight start = new DateMidnight("2010-01-01");
        DateMidnight end = new DateMidnight(new Date());

        //
        // Get months between these dates.
        //
        int months = Months.monthsBetween(start, end).getMonths();

        //
        // Print the result.
        //
        System.out.println("Months between " +
                start.toString("yyyy-MM-dd") + " and " +
                end.toString("yyyy-MM-dd") + " = " +
                months + " month(s)");
    }
}

Here is the output of our program:

Months between 2010-01-01 and 2012-02-07 = 25 month(s)
Wayan Saryada

Wayan Saryada

A programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, JPA, etc. If you need help on Java programming you can hire me on Fiverr.
Wayan Saryada

Leave a Reply