Solved

# Java Calendar: Calculate Number of Months

Posted on 2010-11-17

Hello Experts:

I'm trying to accurately calculate the number of months between two dates and I"m running into a tricky situation:

Let's say I have two dates:

start: 11/01/2010

end: 12/02/2010

I converted these dates strings into a Date object. Now, I'm using the GregorianCalendar to calculate the number of months like so:

int months = ((end.get(Calendar.YEAR) - start.get(Calendar.YEAR)) * end.getMaximum(Calendar.MONTH) ) + end.get(Calendar.MONTH) - start.get(Calendar.MONTH);

This gives me the correct number of months, which is 1.

But if I change the dates like so:

start: 11/15/2010

end: 12/01/2010

I still get the number of months as 1, when really it should be 0.

Can anyone suggest a different and accurate way to calculate the number of months between two dates?

Thank you!