How can I calculate age in Java accurately given Date of birth

alphamalle picture alphamalle · Sep 24, 2015 · Viewed 10.2k times · Source

I am trying to calculate age in java that accounts for months, so just subtracting years will not work. I also want to tell the user if today is their birthday. Here is the code I have so far, but I am afraid it is a bit off. It also will not tell if today is the birthday even though the two dates it's comparing are equal. The way I tried to originally calculate was using milliseconds. The reason you see 2 ways of getting the current date is because I was trying something to get it working, but wanted to show everyone my work so that they could point me in the right direction.

EDIT FOR CLARIFICATION what I mean is 2015-1993 can either be 22 years old or 21 depending if their birthday has already passed this year. I want to be sure that I get the correct age with this in mind.

public class ShowAgeActivity extends AppCompatActivity {

private TextView usersAge;

private static long daysBetween(Date one, Date two)
{
    long difference = (one.getTime()-two.getTime())/86400000; return Math.abs(difference);
}

private Date getCurrentForBirthday()
{
    Date birthday = (Date) this.getIntent().getExtras().get("TheBirthDay");
    int birthdayYear = birthday.getYear() + 1900;
    Calendar cal = Calendar.getInstance();
    cal.set(birthdayYear, Calendar.MONTH, Calendar.DAY_OF_MONTH);
    Date current = cal.getTime();
    return current;
}


protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_show_age);


    Date birthday = (Date) this.getIntent().getExtras().get("TheBirthDay");
      Date currentDay = Calendar.getInstance().getTime();

      long age = daysBetween(birthday,currentDay)/365;

      usersAge =(TextView)findViewById(R.id.ageTextView);

    if (birthday.compareTo(getCurrentForBirthday()) == 0 )
    {
        usersAge.setText("It is your birthday, and your Age is " + String.valueOf(age));
    }

    usersAge.setText("Your Age is " + String.valueOf(age));


    }

}

Answer

Nate picture Nate · Sep 24, 2015

Below is an example of how to calculate a person's age, if today is their birthday, as well as how many days are left until their birthday if today is not their birthday using the new java.time package classes that were included as a part of Java 8.

  LocalDate today             = LocalDate.now();
  LocalDate birthday          = LocalDate.of(1982, 9, 26);
  LocalDate thisYearsBirthday = birthday.with(Year.now());

  long age = ChronoUnit.YEARS.between(birthday, today);

  if (thisYearsBirthday.equals(today))
  {
     System.out.println("It is your birthday, and your Age is " + age);
  }
  else
  {
     long daysUntilBirthday = ChronoUnit.DAYS.between(today, thisYearsBirthday);
     System.out.println("Your age is " + age + ". " + daysUntilBirthday + " more days until your birthday!");
  }