Birthdate based age computation.

This commit is contained in:
Paweł Dyda 2022-11-17 10:01:18 +01:00
parent 4695639b8f
commit d0793f5d11

View File

@ -26,4 +26,16 @@ public class Person {
LocalDate.now().minusYears(18).isAfter(birthDate);
}
public int getAge() {
var birthYear = Objects.requireNonNull(birthDate).getYear();
var now = LocalDate.now();
var baseDifference = now.getYear() - birthYear;
if (birthDate.getMonthValue() > now.getMonthValue() ||
(birthDate.getMonthValue() == now.getMonthValue() &&
birthDate.getDayOfMonth() >= now.getDayOfMonth())) {
return baseDifference;
}
return baseDifference - 1;
}
}