Suggest a feature
×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Java
Posted by: Pascal Surget
Added: Sep 6, 2018 12:49 PM
Views: 1
Tags: no tags
Calculer l'age d'une personne
  1. public int getAge(Date dateOfBirth) {
  2.             Calendar today = Calendar.getInstance();
  3.             Calendar birthDate = Calendar.getInstance();
  4.             birthDate.setTime(dateOfBirth);
  5.             if (birthDate.after(today)) {
  6.                 throw new IllegalArgumentException("You don't exist yet");
  7.             }
  8.             int todayYear = today.get(Calendar.YEAR);
  9.             int birthDateYear = birthDate.get(Calendar.YEAR);
  10.             int todayDayOfYear = today.get(Calendar.DAY_OF_YEAR);
  11.             int birthDateDayOfYear = birthDate.get(Calendar.DAY_OF_YEAR);
  12.             int todayMonth = today.get(Calendar.MONTH);
  13.             int birthDateMonth = birthDate.get(Calendar.MONTH);
  14.             int todayDayOfMonth = today.get(Calendar.DAY_OF_MONTH);
  15.             int birthDateDayOfMonth = birthDate.get(Calendar.DAY_OF_MONTH);
  16.             int age = todayYear - birthDateYear;
  17.  
  18.             // If birth date is greater than todays date (after 2 days adjustment of leap year) then decrement age one year
  19.             if ((birthDateDayOfYear - todayDayOfYear > 3) || (birthDateMonth > todayMonth)){
  20.                 age--;
  21.            
  22.             // If birth date and todays date are of same month and birth day of month is greater than todays day of month then decrement age
  23.             } else if ((birthDateMonth == todayMonth) && (birthDateDayOfMonth > todayDayOfMonth)){
  24.                 age--;
  25.             }
  26.             return age;
  27.         }