简体   繁体   中英

Joda: how to get months and days between two dates

I think I'm missing some subtlety here because everything I'm reading says this should work. I need to get the months and days between two dates in Android. That is to say, how many whole months plus any additional days. I need this as numeric output, not a printed string. Here's what I'm doing, using Joda:

void method(DateTime begin, DateTime end) {
    Period period = Period period = new Period(begin, end);
    final int months = period.getMonths();
    final int additionalDays = period.getDays();

The problem is additionalDays is always zero. For example, July 1 2015 to November 29th 2015 should result in 4 months and 29 days, but I get 4 months and 0 days.

From the documentation Period.getDays() will return 0 if it is unsupported. I am not sure why that would be unsupported, but I'd like to offer a different approach: use the Days and Months classes and their monthsBetween() and daysBetween() methods. Note that you'll have to subtract the months between, too:

// Get months
int months = Months.monthsBetween(begin, end).getMonths();
// Subtract this number of months from the end date so we can calculate days
DateTime newEnd = end.minusMonths(months);
// Get days
int days = Days.daysBetween(begin, newEnd).getDays();

If you don't preform this subtraction in the middle, you'll get incorrect results as you'll get all days.

The javadoc for the Period constructor you used

new Period(begin, end);

states

Creates a period from the given interval endpoints using the standard set of fields.

In other words, it is equivalent to

Period period = new Period(startTime, endTime, PeriodType.standard());

The PeriodType#standard() method returns a PeriodType that supports the weeks field.

Your period, July 1 2015 to November 29th 2015 , is actually 4 months and 28 days, where the 28 days get transformed into 4 weeks. So your Period object is actually of 4 months and 4 weeks.

If you had tried to create a Period from July 1 2015 to November 30th 2015 , you'd have 4 months, 4 weeks, and 1 day.

Instead, create a Period with a PeriodType#yearMonthDay() that only supports years, months, and days fields.

period = new Period(begin, end, PeriodType.yearMonthDay());

then you'd have a Period with 4 months, and 28 days, as it doesn't support weeks.

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