I need to calculate in Java the number of months between two Date objects, but only for the ones which are in the given year.
For example:
01.04.2013 - 30.07.2013, year=2013 => result=4
01.10.2013 - 30.02.2014, year=2013 => result=3
For the second example the result is 3, because only October, November and December are in the given year, 2013. The rest of the months are in 2014.
01.10.2012 - 30.02.2014, year=2013 => result=12
I have this code, but id doesn't work for the following case 01.04.2013 - 30.07.2013, year=2012 => result=0
Calendar startCalendar = new GregorianCalendar();
startCalendar.setTime(c.getStartDate());
Calendar endCalendar = new GregorianCalendar();
endCalendar.setTime(c.getEndDate());
Calendar calculatedStartDate = new GregorianCalendar();
Calendar calculatedEndDate = new GregorianCalendar();
if (startCalendar.get(Calendar.YEAR) < year) {
calculatedStartDate.setTime(new GregorianCalendar(year, Calendar.JANUARY, 1).getTime());
}
else {
calculatedStartDate.setTime(c.getStartDate());
}
if (endCalendar.get(Calendar.YEAR) > year) {
calculatedEndDate.setTime(new GregorianCalendar(year, Calendar.DECEMBER, 31).getTime());
}
else {
calculatedEndDate.setTime(c.getEndDate());
}
int diffMonth = calculatedEndDate.get(Calendar.MONTH) - calculatedStartDate.get(Calendar.MONTH);
return diffMonth + 1;