From dddc78f46f168a1893844de9e647bd59649735e1 Mon Sep 17 00:00:00 2001 From: Patrik Rizell Date: Thu, 9 Jan 2025 08:35:41 +0100 Subject: [PATCH] AB#112: Fixed a bug where Age returned 1 year less than expected. --- Personnummer.Tests/PersonnummerTests.cs | 10 ++++++++++ Personnummer/Personnummer.cs | 5 ++++- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/Personnummer.Tests/PersonnummerTests.cs b/Personnummer.Tests/PersonnummerTests.cs index 527e458..4428084 100644 --- a/Personnummer.Tests/PersonnummerTests.cs +++ b/Personnummer.Tests/PersonnummerTests.cs @@ -236,5 +236,15 @@ public void TestParseTooShort() }).Message ); } + + [Fact] + public void TestEdgeCasesAroundBirthday() + { + var timeProvider = new TestTimeProvider(); //TestTime is 2025-10-05 + Assert.Equal(18, new Personnummer("20071004-3654", new Personnummer.Options() {TimeProvider = timeProvider} ).Age); // Had birthday yesterday + Assert.Equal(18, new Personnummer("20071005-3653", new Personnummer.Options() {TimeProvider = timeProvider} ).Age); // Birthday today + Assert.Equal(17, new Personnummer("20071006-3652", new Personnummer.Options() {TimeProvider = timeProvider} ).Age); // Upcoming Birthday tomorrow + } + } } diff --git a/Personnummer/Personnummer.cs b/Personnummer/Personnummer.cs index 1d8a9a1..637b5f1 100644 --- a/Personnummer/Personnummer.cs +++ b/Personnummer/Personnummer.cs @@ -46,7 +46,10 @@ public int Age var now = _options.DateTimeNow; var age = now.Year - Date.Year; - if (now.Month >= Date.Month && now.Day >= Date.Day) + var hadBirthdayThisYear = (now.Month > Date.Month) || + (now.Month == Date.Month && now.Day >= Date.Day); + + if (!hadBirthdayThisYear) { age--; }