簡體   English   中英

兩個月的Joda日期時間與剩余天數之間的差異

[英]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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM