简体   繁体   中英

Period between dates using Java/Joda

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?

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

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.

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