简体   繁体   中英

Difference Between Two Joda DateTime In Months and Left Over Days

I have a requirement to get the amount of months between two DateTime objects and then get the number of days left over.

Here is how I get the months between:

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

I am unsure how to then find out how many days are left over into the next month. I have tried the following:

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

But this does not have the desired effect.

Use a 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);

The normalization is needed because the period usually creates things like "1 month, 2 weeks and 3 days", and the normalization converts it to "1 month and 17 days". Using the specific DurationFieldType 's above also makes it convert years to months automatically.

Then you can get the number of months and days:

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

Another detail is that when using DateTime objects, the Period will also consider the time (hour, minute, secs) to know if a day has passed.

If you want to ignore the time and consider only the date (day, month and year), don't forget to convert them to LocalDate :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM