0

I would like to find the age of a person - given his birthdate (year, month, day). How can I do this with ThreeTenBP?

EDIT: One option I found is like this

    LocalDate birthdate = LocalDate.of(year, month, day);
    return (int) birthdate.until(LocalDate.now(), ChronoUnit.YEARS);
IgorGanapolsky
  • 26,189
  • 23
  • 116
  • 147

1 Answers1

1

Your code is correct in most countries. It assumes that people born on February 29 have their birthday on March 1 in non-leap years. Read Wikipedia.

Yet, this makes ThreeTen not consistent with itself, unlike Joda-time.

// if birthdate = LocalDate.of(2012, Month.FEBRUARY, 29);
System.out.println (birthdate.until(birthdate.plusYears(1), ChronoUnit.YEARS)); // display 0

If you want that getAge() to be symetric with plusYears(), you could write :

public static int getAge(LocalDate birthdate, LocalDate today)
{
  int age = today.getYears() - birthdate.getYears();
  if (birthdate.plusYears(age).isAfter(today))
      age--;
  return age;
}

See also : How do I calculate someone's age in Java?

Community
  • 1
  • 1