Aujourd'hui, petit problème d'algorithmique simple. Comment calculer en Java l'age d'une personne à ce jour en connaissant sa date de naissance.
Une recherche sur Google ne donne pas de réponse simple. J'espère que celle-ci le sera.
/**
* Compute age of someone. Assume birthday is before today.
* @param birthday Date of birth.
* @param today The date at which you want to calculate age.
* @return age
*/
public int computeAge(Date birthday, Date today) {
Calendar cBirthday = new GregorianCalendar();
Calendar cToday = new GregorianCalendar();
cBirthday.setTime(birthday);
cToday.setTime(today);
int yearDiff = cToday.get(Calendar.YEAR) - cBirthday.get(Calendar.YEAR);
cBirthday.set(Calendar.YEAR, cToday.get(Calendar.YEAR));
if (cBirthday.before(cToday)) {
return yearDiff; //Birthday already celebrated this year
}
else {
return Math.max(0, yearDiff-1); //Need a max to avoid -1 for baby
}
}
Si vous avez plus simple, plus lisible ou si j'ai fait une erreur, merci de compléter.
Vous devez être identifié pour poster un commentaire.
| Lun | Mar | Mer | Jeu | Ven | Sam | Dim |
|---|---|---|---|---|---|---|
| 1 | ||||||
| 2 | 3 | 4 | 5 | 6 | 7 | 8 |
| 9 | 10 | 11 | 12 | 13 | 14 | 15 |
| 16 | 17 | 18 | 19 | 20 | 21 | 22 |
| 23 | 24 | 25 | 26 | 27 | 28 | 29 |
| 30 |