From b0fd3bf373abe05f23b71d3dc49edde75506e5fa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Th=C3=A9o=20LUDWIG?= Date: Tue, 8 Oct 2024 08:47:16 +0200 Subject: [PATCH] feat(date): add `date_get_age` Fixes #7 --- lib/date.c | 8 ++++++++ lib/date.h | 9 +++++++++ test/date_test.c | 27 +++++++++++++++++++++++++++ test/date_test.h | 2 ++ 4 files changed, 46 insertions(+) diff --git a/lib/date.c b/lib/date.c index 5b077b2..3e22204 100644 --- a/lib/date.c +++ b/lib/date.c @@ -329,3 +329,11 @@ struct date *date_get_now_local() { return date; } + +uint16_t date_get_age(struct date *birth_date, struct date *current_date) { + uint16_t age = current_date->year - birth_date->year; + if (current_date->month < birth_date->month || (current_date->month == birth_date->month && current_date->day < birth_date->day)) { + age--; + } + return age; +} diff --git a/lib/date.h b/lib/date.h index dceb869..8a80bde 100644 --- a/lib/date.h +++ b/lib/date.h @@ -338,4 +338,13 @@ struct date *date_get_now_utc(); */ struct date *date_get_now_local(); +/** + * @brief Calculates the age of a person based on their birth date. + * + * @param birth_date + * @return uint16_t + * @since v5.1.0 + */ +uint16_t date_get_age(struct date *birth_date, struct date *current_date); + #endif diff --git a/test/date_test.c b/test/date_test.c index ba03d8b..28181d1 100644 --- a/test/date_test.c +++ b/test/date_test.c @@ -8,6 +8,7 @@ void date_test() { date_get_is_leap_year_test(); date_duration_seconds_between_2_dates_test(); date_to_utc_test(); + date_get_age_test(); } void date_copy_test() { @@ -162,3 +163,29 @@ void date_to_utc_test() { free(iso_string); free(date); } + +void date_get_age_test() { + struct date *birth_date = date_from_iso_string("1980-02-20T00:00:00.000Z"); + struct date *current_date = date_from_iso_string("2018-03-20T00:00:00.000Z"); + assert(date_get_age(birth_date, current_date) == 38); + free(birth_date); + free(current_date); + + birth_date = date_from_iso_string("1980-07-20T00:00:00.000Z"); + current_date = date_from_iso_string("2018-03-20T00:00:00.000Z"); + assert(date_get_age(birth_date, current_date) == 37); + free(birth_date); + free(current_date); + + birth_date = date_from_iso_string("1980-03-20T00:00:00.000Z"); + current_date = date_from_iso_string("2018-03-20T00:00:00.000Z"); + assert(date_get_age(birth_date, current_date) == 38); + free(birth_date); + free(current_date); + + birth_date = date_from_iso_string("1980-03-25T00:00:00.000Z"); + current_date = date_from_iso_string("2018-03-20T00:00:00.000Z"); + assert(date_get_age(birth_date, current_date) == 37); + free(birth_date); + free(current_date); +} diff --git a/test/date_test.h b/test/date_test.h index d3ec9b7..a415018 100644 --- a/test/date_test.h +++ b/test/date_test.h @@ -21,4 +21,6 @@ void date_duration_seconds_between_2_dates_test(); void date_to_utc_test(); +void date_get_age_test(); + #endif