Wednesday, January 26, 2011

Months between two dates - Java Implementation

A code snippet that will accept two java.util.Date objects and return the number of months between the two dates.

public int getNumberOfMonths(Date fromDate, Date toDate){
int monthCount=0;
Calendar cal = Calendar.getInstance();
cal.setTime(fromDate);
int c1date=cal.get(Calendar.DATE);
int c1month=cal.get(Calendar.MONTH);
int c1year=cal.get(Calendar.YEAR);
cal.setTime(toDate);
int c2date=cal.get(Calendar.DATE);
int c2month=cal.get(Calendar.MONTH);
int c2year=cal.get(Calendar.YEAR);

monthCount = ((c2year-c1year)*12) + (c2month-c1month) + ((c2date>=c1date)?1:0);

return monthCount;
}


Hope this helps!

2 comments:

Anonymous said...

this wont work for a leap year, this gives a result as 13 monthw

Anonymous said...

Calendar calendar = new GregorianCalendar();
calendar.setTime(fromDate);
calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) + months);
return calendar.before(new GregorianCalendar()); :P