两个 Joda DateTime 之间的差异(以月为单位)和剩余天数

Difference Between Two Joda DateTime In Months and Left Over Days

我需要获取两个 DateTime 对象之间的月数,然后获取剩余的天数。

以下是我如何获得之间的月份:

Months monthsBetween = Months.monthsBetween(dateOfBirth,endDate);

我不确定如何找出下个月还剩多少天。我尝试了以下方法:

int offset = Days.daysBetween(dateOfBirth,endDate)
              .minus(monthsBetween.get(DurationFieldType.days())).getDays();

但这并没有达到预期的效果。

使用 org.joda.time.Period:

// fields used by the period - use only months and days
PeriodType fields = PeriodType.forFields(new DurationFieldType[] {
        DurationFieldType.months(), DurationFieldType.days()
    });
Period period = new Period(dateOfBirth, endDate)
    // normalize to months and days
    .normalizedStandard(fields);

需要规范化,因为周期通常会产生“1 个月 2 周 3 天”之类的东西,规范化会将其转换为“1 个月 17 天”。使用上面的特定 DurationFieldType 也可以自动将年转换为月。

然后可以得到月数和天数:

int months = period.getMonths();
int days = period.getDays();

另一个细节是,当使用 DateTime 对象时,Period 也会考虑时间(小时、分钟、秒)来判断一天是否过去了。

如果你想忽略时间而只考虑日期(日、月、年),别忘了将它们转换为LocalDate:

// convert DateTime to LocalDate, so time is ignored
Period period = new Period(dateOfBirth.toLocalDate(), endDate.toLocalDate())
    // normalize to months and days
    .normalizedStandard(fields);