Calculate Months Between Two Dates in Java – 用 Java 计算两个日期之间的月份

最后修改: 2023年 12月 28日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

Calculating month intervals between dates is a common programming task. The Java standard library and third-party libraries provide classes and methods to calculate months between two dates.

计算日期之间的月份间隔是一项常见的编程任务。Java 标准库和第三方库提供了计算两个日期之间月份的类和方法。

In this tutorial, we’ll delve into details of how to use the legacy Date API, Date Time API, and Joda-Time library to calculate month intervals between two dates in Java.

在本教程中,我们将详细介绍如何使用传统的 Date API、Date Time APIJoda-Time 库来计算 Java 中两个日期之间的月份间隔。

2. Impact of Day Value

2.日值的影响

When calculating the month interval between two dates, the day value of the dates impacts the result.

计算两个日期之间的月份间隔时,日期的日值会影响计算结果。

By default, the Java standard library and Joda-Time library consider the day value. If the day value of the end date is less than the day value of the start day, the final month isn’t counted as a full month and is excluded from the month interval:

默认情况下,Java 标准库和 Joda-Time 库会考虑日值。如果结束日期的日值小于开始日期的日值,则最后一个月不计入整月,并从月份间隔中排除

LocalDate startDate = LocalDate.parse("2023-05-31");
LocalDate endDate = LocalDate.parse("2023-11-28");

In the code above, the day value of the end date is less than the day value of the start date. Therefore, the final month won’t count as a full month.

在上面的代码中,结束日期的日值小于开始日期的日值。因此,最后一个月不能算作整月。

However, if the day value of the end date is equal to or greater than the day value of the day value of the start date, the final month is considered a full month and included in the interval:

但是,如果结束日期的日值等于或大于开始日期的日值,则最后一个月被视为整月并包含在区间中

LocalDate startDate = LocalDate.parse("2023-05-15");
LocalDate endDate = LocalDate.parse("2023-11-20");

In some cases, we may decide to ignore the day value completely and only consider the month value difference between the two dates.

在某些情况下,我们可能会决定完全忽略日值,只考虑两个日期之间的月值差异。

In the subsequent sections, we’ll see how to calculate month intervals between two dates with or without considering the day value.

在随后的章节中,我们将了解如何计算两个日期之间的月份间隔,无论是否考虑日值。

3. Using Legacy Date API

3.使用旧版日期应用程序接口

When using the legacy Date API, we need to create a custom method to calculate month intervals between two dates. With the Calendar class, we can calculate the month interval between two dates using the Date class.

在使用传统的日期 API 时,我们需要创建一个自定义方法来计算两个日期之间的月份间隔。通过 Calendar 类,我们可以使用 Date 类计算两个日期之间的月份间隔

3.1. Without the Day Value

3.1.无日值

Let’s write a method that uses the Calendar and Date classes to calculate the month interval between two Date objects without considering the day value:

让我们编写一个方法,使用 CalendarDate 类计算两个 Date 对象之间的月份间隔,而不考虑日值:

int monthsBetween(Date startDate, Date endDate) {
    if (startDate == null || endDate == null) {
        throw new IllegalArgumentException("Both startDate and endDate must be provided");
    }

    Calendar startCalendar = Calendar.getInstance();
    startCalendar.setTime(startDate);
    int startDateTotalMonths = 12 * startCalendar.get(Calendar.YEAR) 
      + startCalendar.get(Calendar.MONTH);

    Calendar endCalendar = Calendar.getInstance();
    endCalendar.setTime(endDate);
    int endDateTotalMonths = 12 * endCalendar.get(Calendar.YEAR) 
      + endCalendar.get(Calendar.MONTH);

    return endDateTotalMonths - startDateTotalMonths;
}

This method takes the start date and end date as arguments. First, we create a Calendar instance and pass the Date object to it. Next, we calculate the total months of each date by converting the year to month and adding it to the current month value.

此方法将开始日期和结束日期作为参数。首先,我们创建一个 Calendar 实例,并将 Date 对象传递给它。接下来,我们将年份转换为月份,并将其与当前月份值相加,从而计算出每个日期的总月份数

Finally, we find the difference between the two dates.

最后,我们找出两个日期之间的差值。

Let’s write a unit test for the method:

让我们为该方法编写一个单元测试:

@Test
void whenCalculatingMonthsBetweenUsingLegacyDateApi_thenReturnMonthsDifference() throws ParseException {
    MonthInterval monthDifference = new MonthInterval();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    
    Date startDate = sdf.parse("2016-05-31");
    Date endDate = sdf.parse("2016-11-30");
    int monthsBetween = monthDifference.monthsBetween(startDate, endDate);
    
    assertEquals(6, monthsBetween);
}

In the code above, we create a SimpleDateFormat object to format the date. Next, we pass the Date object to the monthsBetween() to calculate the month interval.

在上面的代码中,我们创建了一个 SimpleDateFormat 对象来格式化日期。接下来,我们将 Date 对象传递给 monthsBetween() 以计算月份间隔。

Finally, we assert that the output is equal to the expected result.

最后,我们断言输出结果等于预期结果。

3.2. With the Day Value

3.2.日值

Also, let’s see an example code that puts the day value into consideration:

另外,让我们看一个将日值考虑在内的示例代码:

int monthsBetweenWithDayValue(Date startDate, Date endDate) {
    if (startDate == null || endDate == null) {
        throw new IllegalArgumentException("Both startDate and endDate must be provided");
    }
    
    Calendar startCalendar = Calendar.getInstance();
    startCalendar.setTime(startDate);
    
    int startDateDayOfMonth = startCalendar.get(Calendar.DAY_OF_MONTH);
    int startDateTotalMonths = 12 * startCalendar.get(Calendar.YEAR) 
      + startCalendar.get(Calendar.MONTH);
        
    Calendar endCalendar = Calendar.getInstance();
    endCalendar.setTime(endDate);
    
    int endDateDayOfMonth = endCalendar.get(Calendar.DAY_OF_MONTH);
    int endDateTotalMonths = 12 * endCalendar.get(Calendar.YEAR) 
      + endCalendar.get(Calendar.MONTH);

    return (startDateDayOfMonth > endDateDayOfMonth) 
      ? (endDateTotalMonths - startDateTotalMonths) - 1 
      : (endDateTotalMonths - startDateTotalMonths);
}

Here, we add a condition to check if the start date day value is greater than the end date day value. Then, we adjust the month interval based on the condition.

在这里,我们添加一个条件,检查开始日期日值是否大于结束日期日值。然后,我们根据条件调整月份间隔。

Here’s a unit test for the method:

下面是该方法的单元测试:

@Test
void whenCalculatingMonthsBetweenUsingLegacyDateApiDayValueConsidered_thenReturnMonthsDifference() throws ParseException {
    MonthInterval monthDifference = new MonthInterval();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    
    Date startDate = sdf.parse("2016-05-31");
    Date endDate = sdf.parse("2016-11-28");
    int monthsBetween = monthDifference.monthsBetweenWithDayValue(startDate, endDate);
    
    assertEquals(5, monthsBetween);
}

Since the end date day value is less than the start date day value, the final month doesn’t count as a full month.

由于结束日期日值小于开始日期日值,因此最后一个月不算整月。

4. Using the Date Time API

4.使用日期时间应用程序接口

Since Java 8, the Date Time API provides options to get the month interval between two dates. We can use the Period class and ChronoUnit enum to compute the month interval between two dates.

自 Java 8 起,日期时间 API 提供了获取两个日期之间月份间隔的选项。我们可以使用 Period 类和 ChronoUnit 枚举计算两个日期之间的月份间隔。

4.1. The Period Class

4.1.周期

The Period class provides a static method named between() to calculate month intervals between two dates. It accepts two arguments representing the start date and the end date. The day value of the date impacts the month interval when using the Period class:

Period 类提供了一个名为 between() 的静态方法,用于计算两个日期之间的月份间隔。该方法接受两个参数,分别代表开始日期和结束日期。使用 Period 类时,日期的日值会影响月份间隔:

@Test
void whenCalculatingMonthsBetweenUsingPeriodClass_thenReturnMonthsDifference() {
    Period diff = Period.between(LocalDate.parse("2023-05-25"), LocalDate.parse("2023-11-23"));
    assertEquals(5, diff.getMonths());
}

Considering the day’s value in the dates, between() returns a difference of five months. The day value of the end date is less than the day value of the start date. Hence, the final month doesn’t count as a full month.

考虑到日期中的日值,between() 返回五个月的差值。结束日期的日值小于开始日期的日值。因此,最后一个月不算整月。

However, if we intend to ignore the day value of the dates, we can set the LocalDate objects to the first day of the month:

但是,如果我们打算忽略日期的日值,我们可以将 LocalDate 对象设置为每月的第一天:

@Test
void whenCalculatingMonthsBetweenUsingPeriodClassAndAdjsutingDatesToFirstDayOfTheMonth_thenReturnMonthsDifference() {
    Period diff = Period.between(LocalDate.parse("2023-05-25")
      .withDayOfMonth(1), LocalDate.parse("2023-11-23")
      .withDayOfMonth(1));
    assertEquals(6, diff.getMonths());
}

Here, we invoke the withDayOfMonth() method on the LocalDate object to set the dates to the beginning of the month.

在此,我们调用 LocalDate 对象上的 withDayOfMonth() 方法,将日期设置为月初。

4.2. The ChronoUnit Enum

4.2.ChronoUnit 枚举

The ChronoUnit enum provides a constant named MONTHS and a static method named between() to compute the month interval between two dates.

ChronoUnit 枚举提供了一个名为 MONTHS 的常量和一个名为 between() 的静态方法,用于计算两个日期之间的月份间隔。

Similar to the Period class, the ChronoUnit enum also considers the day value in the two dates:

Period 类类似,ChronoUnit 枚举也考虑了两个日期中的日值:

@Test
void whenCalculatingMonthsBetweenUsingChronoUnitEnum_thenReturnMonthsDifference() {
    long monthsBetween = ChronoUnit.MONTHS.between(
      LocalDate.parse("2023-05-25"), 
      LocalDate.parse("2023-11-23")
    );
    assertEquals(5, monthsBetween);
}

Also, if we intend to ignore the day value, we can set the date objects to the first day of the month using the withDayOfMonth() method:

此外,如果我们打算忽略日期值,可以使用 withDayOfMonth() 方法将日期对象设置为每月的第一天:

@Test
void whenCalculatingMonthsBetweenUsingChronoUnitEnumdSetTimeToFirstDayOfMonth_thenReturnMonthsDifference() {
    long monthsBetween = ChronoUnit.MONTHS.between(LocalDate.parse("2023-05-25")
      .withDayOfMonth(1), LocalDate.parse("2023-11-23")
      .withDayOfMonth(1));
    assertEquals(6, monthsBetween);
}

Finally, we can also use YearMonth.from() method with ChronoUnit enum to ignore the day value:

最后,我们还可以使用 YearMonth.from() 方法和 ChronoUnit 枚举来忽略日值:

@Test
void whenCalculatingMonthsBetweenUsingChronoUnitAndYearMonth_thenReturnMonthsDifference() {
    long diff = ChronoUnit.MONTHS.between(
      YearMonth.from(LocalDate.parse("2023-05-25")), 
      LocalDate.parse("2023-11-23")
    );
    assertEquals(6, diff);
}

In the code above, we use the YearMonth.from() method to consider only the year and month values while computing the month between the two dates.

在上面的代码中,我们使用 YearMonth.from() 方法在计算两个日期之间的月份时,只考虑年和月值。

5. Using the Joda Time Library

5.使用 Joda 时间库

The Joda-Time library provides the Months.monthsBetween() method to find month intervals between two dates. To use the Joda-Time library, let’s add its dependency to the pom.xml:

Joda-Time 库提供了 Months.monthsBetween() 方法来查找两个日期之间的月份间隔。要使用 Joda-Time 库,让我们将其 依赖关系添加到 pom.xml 中:

<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
    <version>2.12.5</version>
</dependency>

Just like the Date Time API, it considers the day value of the dates objects by default:

就像日期时间 API 一样,默认情况下它也会考虑日期对象的日值:

@Test
void whenCalculatingMonthsBetweenUsingJodaTime_thenReturnMonthsDifference() {
    DateTime firstDate = new DateTime(2023, 5, 25, 0, 0);
    DateTime secondDate = new DateTime(2023, 11, 23, 0, 0);
    int monthsBetween = Months.monthsBetween(firstDate, secondDate).getMonths();
    assertEquals(5, monthsBetween);
}

In the code above, we create two date objects with a set date. Next, we pass the date objects to the monthsBetween() method and invoke getMonths() on it.

在上面的代码中,我们创建了两个日期对象,并设定了日期。然后,我们将日期对象传递给 monthsBetween() 方法,并调用 getMonths() 方法。

Finally, we assert that the return month interval is equal to the expected value.

最后,我们断言回报月区间等于预期值。

If we intend not to consider the day value, we can invoke the withDayOfMonth() method on the DateTime objects and set the day to the first day of the month:

如果我们不打算考虑日值,可以调用 DateTime 对象上的 withDayOfMonth() 方法,将日设置为每月的第一天:

@Test
void whenCalculatingMonthsBetweenUsingJodaTimeSetTimeToFirstDayOfMonth_thenReturnMonthsDifference() {
    DateTime firstDate = new DateTime(2023, 5, 25, 0, 0).withDayOfMonth(1);
    DateTime secondDate = new DateTime(2023, 11, 23, 0, 0).withDayOfMonth(1);
        
    int monthsBetween = Months.monthsBetween(firstDate, secondDate).getMonths();
    assertEquals(6, monthsBetween);
}

Here, we set the day of the two date objects to the first day of the month to avoid the day value impacting the expected result.

在这里,我们将两个日期对象的日设置为每月的第一天,以避免日值影响预期结果。

6. Conclusion

6.结论

In this article, we learned ways of calculating the month interval between two date objects using the standard library and a third-party library. Also, we saw how to calculate month intervals between dates with and without considering the day value of the dates.

在本文中,我们学习了使用标准库和第三方库计算两个日期对象之间的月份间隔的方法。此外,我们还了解了如何在考虑和不考虑日期日值的情况下计算日期之间的月份间隔。

The choice to include or ignore the day value depends on our goal and specific requirements. Also, the Date Time API provides different options, and it’s recommended because it’s easier to use and doesn’t require external dependency.

选择包含还是忽略日期值取决于我们的目标和具体要求。此外,日期时间应用程序接口提供了不同的选项,我们推荐使用它,因为它更易于使用,而且不需要外部依赖。

As usual, the complete source code for the examples is available over on GitHub.

与往常一样,这些示例的完整源代码可在 GitHub 上获取。