Pages - Menu

Calculate age in .Net

Scope

I wanted to calculate a person's age in .Net. I am a little disappointed there is no SQL-like DateDiff function in .Net Framework.
If you search on Google, you will find these with high rank and votes.
I didn't like the idea of converting dates to float back and forth so that you can add milliseconds to the date or trying to divide the date by 365.242199 so that we are catering leap years that occur every 4 years but not the 100th but then the 400th year again and so on….

Solution

If someone ask me how old am I, it is simple logical process.
  • What year am I in? 
  • What year did I born? 
  • And have I had my birthday this year yet?
With this in mind, the pseudocode is simple. If I didn’t pass my birthday, then my age is calculated by this year but take out 1.

public int? Age
{
    get
    {
        return (DateTime.Today.DayOfYear >= DOB.DayOfYear)
                    ? (DateTime.Today.Year - DOB.Year)
                    : (DateTime.Today.Year - DOB.Year - 1);
    }
}

No comments:

Post a Comment