How To: Calculate the age (in years) of anything using extension methods

Friday, January 11, 2008

When creating an application that requires a person’s age, we typically store the date of birth and calculate their age in years from that.  I usually store my user’s date of birth in a property of type DateTime.  To make it easy to calculate the user’s age based on this property, I decided to take advantage of .NET’s new extension methods feature.  By adding an extension method to .NET’s native DateTime type, we can quickly calculate the age of any object that has a DateTime property. 


We will create two extension methods.  One will accept no parameters and return the age based on the current date.  The overload of this method will accept an future date to base the age calculation on.  This would be useful if you wanted to know what the person’s age will be on some future date.  As we see below, they are very straightforward.





Once we have that, we just need to import the namespace that our extension methods are in.  All your DateTime types will now have this method available via intellisense.




To see the effect of our new extension method, let’s see what Jim Morrison’s current age would be followed by how old he’ll be in a number of days.  Finally, let’s see how long ago the US declared independence from the British.





The previous code will produce the following output: 


 


If you want to find out more about authoring your own extension methods, check out this article


Hope this helps.


 


5 Comments

  1. vikram says:

    This was a good use of extension method

  2. http:// says:

    Wouln’t the extension method be better named GetAgeInYears()?

  3. MikeBosch says:

    Yes. That may be a more appropriate method name.

  4. http:// says:

    Isn’t the use of:

    int age = (onDate – birthDate).Year;

    easier to determine the age?

    DateTime has an overloaded operators that handles the totaling and subtraction of dates.

  5. http:// says:

    I’m new to asp.net and I was confused by all the code above and after goofing around for a little bit I was able to get this code to work. All I’m doing is determing the persons age based on their Birth Date that I capture when the user signs up on my site. I save the Birth Date as a datetime string. Below is the code I just used.

    int ageindays = (DateTime.Now – pc.BirthDate).Days;
    int age = ageindays / 365;

Leave a Reply