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--; }