ciao ho qui una funzione che fa al caso tuo..
in questo caso calcolo la differenza in giorni, nn dovresti aver problemi a metterla in mesi
codice:/** * METODO PER CALCOLO GIORNI DI DIFFERENZA TRA 2 DATE CON FORMATO SPECIFICO * * Il metodo calcola e restituisce il numero di giorni di differenza tra 2 date * * @param sdate1 * data(ora) da cui sottrarre * @param sdate2 * data(ora) da sottrarre * @param format * formato delle date per controllo * @param tz * timezone * @return * giorni di differenza * @throws ParseException */ public static int diffDayFrom2Date(String sdate1, String sdate2, String format, TimeZone tz) throws ParseException{ SimpleDateFormat df = new SimpleDateFormat(format); Date date1 = null; Date date2 = null; date1 = df.parse(sdate1); date2 = df.parse(sdate2); Calendar cal1 = null; Calendar cal2 = null; if (tz == null){ cal1=Calendar.getInstance(); cal2=Calendar.getInstance(); }else{ cal1=Calendar.getInstance(tz); cal2=Calendar.getInstance(tz); } // different date might have different offset cal1.setTime(date1); long ldate1 = date1.getTime() + cal1.get(Calendar.ZONE_OFFSET) + cal1.get(Calendar.DST_OFFSET); cal2.setTime(date2); long ldate2 = date2.getTime() + cal2.get(Calendar.ZONE_OFFSET) + cal2.get(Calendar.DST_OFFSET); // Use integer calculation, truncate the decimals int hr1 = (int)(ldate1/3600000); //60*60*1000 int hr2 = (int)(ldate2/3600000); int days1 = (int)hr1/24; int days2 = (int)hr2/24; int dateDiff = days2 - days1; int weekOffset = (cal2.get(Calendar.DAY_OF_WEEK) - cal1.get(Calendar.DAY_OF_WEEK))<0 ? 1 : 0; int weekDiff = dateDiff/7 + weekOffset; int yearDiff = cal2.get(Calendar.YEAR) - cal1.get(Calendar.YEAR); int monthDiff = yearDiff * 12 + cal2.get(Calendar.MONTH) - cal1.get(Calendar.MONTH); // RITORNA DIFFERENZA DATE return dateDiff; }


Rispondi quotando