How to calculate age in C#

Seems like a simple thing, but the fact that you need to subtract a year if the person hasn’t had their birthday yet in the current year made it more involved. There were a lot of different ways to do it online, some of them more clunky than others. I cobbled this together from the various posts I found (assume a Person object with a DOB field).

public int Age {

  • get {
    • var now = DateTime.Now;
    • var age = now.Year - this.DOB.Year;
    • return (this.DOB.DayOfYear <= now.DayOfYear) ? age : age - 1;
  • }



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s