Reputation: 5849
I have 2 joda dates as follows:
org.joda.time.DateTime a;
org.joda.time.DateTime b;
I want the difference between the 2 dates in terms of Years, months and days (eg. 0 years, 2 months, 5 days).
I can use the org.joda.time.Days.daysBetween(a, b)
or monthsBetween(a, b)
or yearsBetween(a, b)
to get the whole values of each respectively.
Since a month does have number of fixed number of days, how can I calculate this?
Eg. If I get monthsbetween = 2
and daysbetween = 65
, how can I write this as "2 months and x days"
Is there any other way to get this?
Upvotes: 0
Views: 244
Reputation: 459
Try this:
Calendar ca = Calendar.getInstance();
ca.setTime(a);
Calendar cb = Calendar.getInstance();
cb.setTime(b);
System.out.printf("%d months and %d days"
, ca.get(Calendar.MONTH) - cb.get(Calendar.MONTH)
, ca.get(Calendar.DAY_OF_MONTH) - cb.get(Calendar.DAY_OF_MONTH));
Upvotes: 1
Reputation: 3
Im not too familiar with Joda, but it looks like your best option is to divide the days left by 30.5, and then round it up back to a whole integer. Like so:
double daysDivided = daysbetween / 30.5;
int daysbetweenFixed = (int) daysDivided;
System.out.printf("%d months and %d days", monthsbetween, daysbetweenFixed);
//optional output ^
I'm sure you would know i chose 30.5 because it seems like the a good average month length, excluding February. Because there is no set length of a month this is the best we can do with only these integers.
Upvotes: 0