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