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!
Subscribe to:
Post Comments (Atom)
2 comments:
this wont work for a leap year, this gives a result as 13 monthw
Calendar calendar = new GregorianCalendar();
calendar.setTime(fromDate);
calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) + months);
return calendar.before(new GregorianCalendar()); :P
Post a Comment