How to calculate a person's age based on date of birth in C#?
Hello everyone! I'm a beginner C# developer and I've encountered a seemingly simple task — calculating a user's age based on their date of birth. I have a `DateTime birthday` variable (e.g., `new DateTime(1990, 5, 15)`), and I need to get an integer number of full years as of today.
I tried the most obvious way — subtract the date of birth from the current date and take the difference in years:
```csharp
DateTime today = DateTime.Today;
int age = today.Year - birthday.Year;
```
But this doesn't work correctly! If the person's birthday hasn't occurred yet this year, the age is overestimated by 1 year. For example, if today is January 1, 2025, and the birthday is May 15, 1990, my code will output 35 years, even though the person is actually 34.
I also tried using `TimeSpan`: