Java Calendar: Calculate Number of Months
Posted on 2010-11-17
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:
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:
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?