From d0793f5d11fce1524ab93c0c349c217e7fc01e44 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Dyda?= Date: Thu, 17 Nov 2022 10:01:18 +0100 Subject: [PATCH] Birthdate based age computation. --- .../src/main/java/pl/amu/edu/demo/data/Person.java | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/demo/03/src/main/java/pl/amu/edu/demo/data/Person.java b/demo/03/src/main/java/pl/amu/edu/demo/data/Person.java index 36a12de..64580b6 100644 --- a/demo/03/src/main/java/pl/amu/edu/demo/data/Person.java +++ b/demo/03/src/main/java/pl/amu/edu/demo/data/Person.java @@ -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; + } + }