Java如何获取Joda-Time中两个日期之间的月数?
下面的代码向您展示如何使用Months该类来计算两个日期之间的月份差异。
package org.nhooo.example.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) { //创建开始日期和结束日期的实例。 DateMidnight start = new DateMidnight("2019-01-01"); DateMidnight end = new DateMidnight(new Date()); //在这些日期之间获取月份。 int months = Months.monthsBetween(start, end).getMonths(); //打印结果。 System.out.println("Months between " + start.toString("yyyy-MM-dd") + " and " + end.toString("yyyy-MM-dd") + " = " + months + " month(s)"); //使用LocalDate对象。 LocalDate date1 = LocalDate.parse("2019-03-01"); LocalDate date2 = LocalDate.now(); months = Months.monthsBetween(date1, date2).getMonths(); //打印结果。 System.out.println("Months between " + date1.toString("yyyy-MM-dd") + " and " + date2.toString("yyyy-MM-dd") + " = " + months + " month(s)"); } }
这是我们程序的输出:
Months between 2019-01-01 and 2019-07-22 = 6 month(s) Months between 2019-03-01 and 2019-07-22 = 4 month(s)
Maven依赖
<!-- https://search.maven.org/remotecontent?filepath=joda-time/joda-time/2.10.3/joda-time-2.10.3.jar --> <dependency> <groupId>joda-time</groupId> <artifactId>joda-time</artifactId> <version>2.10.3</version> </dependency>