Ce code calcul l'écart en années / mois / jours (complets) entre 2 dates :
Ajouter les imports suivants :
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class ecartDate {
static int UN = 1;
static int DOUZE = 12;
public static void main(String[] args) {
Calendar calStr1 = Calendar.getInstance();
Calendar calStr2 = Calendar.getInstance();
Calendar calStr0 = Calendar.getInstance();
Date date1 = null;
Date date2 = null;
int nbMois = 0;
int nbAnnees = 0;
long nbJours = 0;
try {
date1 = new SimpleDateFormat("dd/MM/yyyy").parse("25/01/2006");
} catch (ParseException e) {
e.printStackTrace();
}
try {
date2 = new SimpleDateFormat("dd/MM/yyyy").parse("11/02/2014");
} catch (ParseException e) {
e.printStackTrace();
}
if (date1.equals(date2)) {
return;
}
calStr1.setTime(date1);
calStr2.setTime(date2);
nbMois = 0;
while (calStr1.before(calStr2)) {
calStr1.add(GregorianCalendar.MONTH, UN);
if (calStr1.before(calStr2) || calStr1.equals(calStr2)) {
nbMois++;
}
}
nbAnnees = (nbMois / DOUZE);
nbMois = (nbMois - (nbAnnees * DOUZE));
calStr0 = Calendar.getInstance();
calStr0.setTime(date1);
calStr0.add(GregorianCalendar.YEAR, nbAnnees);
calStr0.add(GregorianCalendar.MONTH, nbMois);
nbJours = (calStr2.getTimeInMillis() - calStr0.getTimeInMillis()) / 86400000;
System.out.print("Nb Annees : "+nbAnnees+"\n");
System.out.print("Nb Mois : "+nbMois+"\n");
System.out.print("Nb Jours : "+nbJours+"\n");
}
}