在几个月内和几天内剩下的两个Joda DateTime之间的差异



我需要在两个 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 s也使其自动转换为几个月。

然后您可以获得几个月的数量:

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

另一个细节是,当使用DateTime对象时,Period还将考虑时间(小时,分钟,SEC(知道一天是否过去了。

如果您想忽略时间而仅考虑日期(日,月和年(,请不要忘记将它们转换为LocalDate

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

最新更新