Twenty C# Questions Explained: (14) How do I calculate someone’s age in C#?

Sign in to queue

The Discussion

  • User profile image
    Stelzi79

    This example only works on a accuracy of month. It would be better to calculate the birthday this year and compare this with the current date and if the birthday is later in this year then subtract one from the age.

          DateTime birthdayInThisYear = new DateTime(curDate.Year, birthday.Month, birthday.Day);
    
          if (birthdayInThisYear > curDate)
          {
            age--;
          }

Add Your 2 Cents