The code below show you how to use the Months
class to calculate the different in months between two dates.
package org.kodejava.joda;
import org.joda.time.DateMidnight;
import org.joda.time.LocalDate;
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("2021-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)");
// Using LocalDate object.
LocalDate date1 = LocalDate.parse("2021-03-01");
LocalDate date2 = LocalDate.now();
months = Months.monthsBetween(date1, date2).getMonths();
// Print the result.
System.out.println("Months between " +
date1.toString("yyyy-MM-dd") + " and " +
date2.toString("yyyy-MM-dd") + " = " +
months + " month(s)");
}
}
Here is the output of our program:
Months between 2021-01-01 and 2021-10-29 = 9 month(s)
Months between 2021-03-01 and 2021-10-29 = 7 month(s)
Maven Dependencies
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.12.5</version>
</dependency>
Latest posts by Wayan (see all)
- How do I create a string of repeated characters? - September 1, 2023
- How do I convert datetime string with optional part to a date object? - August 28, 2023
- How do I split large excel file into multiple smaller files? - April 15, 2023