【问题标题】:Difference Between Two Joda DateTime In Months and Left Over Days两个 Joda DateTime 月数和剩余天数之间的差异
【发布时间】:2018-07-30 20:09:56
【问题描述】:

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

这里是我如何得到之间的月份:

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

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

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

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

【问题讨论】:

    标签: java android jodatime period date-difference


    【解决方案1】:

    使用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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-23
      • 1970-01-01
      • 1970-01-01
      • 2012-07-15
      相关资源
      最近更新 更多