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
<!-- https://search.maven.org/remotecontent?filepath=joda-time/joda-time/2.11.2/joda-time-2.11.2.jar -->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.11.2</version>
</dependency>
Latest posts by Wayan (see all)
- How do I build simple search page using ZK and Spring Boot? - March 8, 2023
- How do I calculate days between two dates excluding weekends and holidays? - January 12, 2023
- How do I discover the quarter of a given date? - January 11, 2023