StaleElementException
StaleElementException

Reputation: 270

how to get exact month difference in Joda-Time after adding no.of days

I'm trying to find no.of months between two dates. any help appreciated. I'm using Joda-Time for the below example.

DateMidnight start = new DateMidnight(new Date()); 
DateMidnight dtEndDate  = start.plusDays(11);   //adding Days

int months = Months.monthsBetween(start, dtEndDate).getMonths();

System.out.println("Months between " +
                    start.toString("yyyy-MM-dd") + " and " +
                    dtEndDate.toString("yyyy-MM-dd") + " = " +
                    months + " month(s)");

The above code returning '0' for 2013-Feb-18 to 2013-Mar-01

I can't add +1 to months as i need to find difference in same month, also i need to find difference between two elapsed periods i.e between '2012-Dec-04' and '2013-Jan-06' should return -1;

scenario1:

date1:  2013-02-18
    date1.plusDays(11);
date2:  2013-03-01
Output : 0 month(s)   //but I need as 1 Month

scenario2:
date1:  2013-02-18
    date1.plusDays(1);
date2:  2013-02-19
Output : 0 month(s)   //returns correctly exactly what I need

scenario3:
date1:  2013-03-18
date2:  2013-02-19
Output should be : -1 month(s)

Upvotes: 1

Views: 3526

Answers (1)

Hari Menon
Hari Menon

Reputation: 35395

Set the day of month to 1 for both dates before comparing:

startModified = start.withDayOfMonth(1); 
endModified = end.withDayOfMonth(1);
int months = Months.monthsBetween(startModified, endModified).getMonths();

Upvotes: 5

Related Questions