From 90f6d26f6d8c3f650c8c70cbb789a3b50980b7c2 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Mon, 26 Aug 2024 13:37:54 +0300 Subject: [PATCH] add function to calculate age --- internal/utils/age.go | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 internal/utils/age.go diff --git a/internal/utils/age.go b/internal/utils/age.go new file mode 100644 index 0000000..56c3e2b --- /dev/null +++ b/internal/utils/age.go @@ -0,0 +1,21 @@ +package utils + +import "time" + + +func CalculateAge(birthdate, today time.Time) int { + today = today.In(birthdate.Location()) + ty, tm, td := today.Date() + today = time.Date(ty, tm, td, 0, 0, 0, 0, time.UTC) + by, bm, bd := birthdate.Date() + birthdate = time.Date(by, bm, bd, 0, 0, 0, 0, time.UTC) + if today.Before(birthdate) { + return 0 + } + age := ty - by + anniversary := birthdate.AddDate(age, 0, 0) + if anniversary.After(today) { + age-- + } + return age +} \ No newline at end of file