代码之家  ›  专栏  ›  技术社区  ›  StuStirling

两个Joda DateTime之间的月差和剩余天数

  •  2
  • StuStirling  · 技术社区  · 8 年前

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

    以下是我如何计算以下月份之间的月份:

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

    我不知道怎样才能知道下个月还剩多少天。我尝试了以下方法:

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

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

    1 回复  |  直到 8 年前
        1
  •  2
  •   user9386070    8 年前

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