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!