Calculate Age in Years using C# or VB.NET

I was recently checking out some scripts to calculate the Age of a person in years and came across a simple piece of code shared by NeilPric. Here’s the code for your reference:

C#

static void Main(string[] args)
{
DateTime dob = DateTime.Parse("04/24/1979");

int ageInYrs = DateTime.Now.Year - dob.Year;
if (DateTime.Now.Month < dob.Month
(DateTime.Now.Month == dob.Month &&
DateTime.Now.Day < dob.Day))
ageInYrs--;
Console.WriteLine(ageInYrs);
Console.ReadLine();
}

VB.NET

Sub Main(ByVal args() As String)
Dim dob As Date = Date.Parse("04/24/1979")

Dim ageInYrs As Integer = Date.Now.Year - dob.Year
If Date.Now.Month < dob.Month _
OrElse (Date.Now.Month = dob.Month AndAlso Date.Now.Day < dob.Day) Then
ageInYrs -= 1
End If
Console.WriteLine(ageInYrs)
Console.ReadLine()
End Sub

OUTPUT

30



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

1 comment:

samuel fernandes said...

Hi!

This is a nice article. Thank for sharing your knowledge. There are some other links related to calculating exact age in years, months and days, i hope this is a very useful for developers.

http://www.mindstick.com/Blog/473/Calculate%20Age%20in%20ASP%20Net%20C

http://www.mithilasoftware.com/Blog/post/Calculating-age-in-years-and-months-in-aspnet-c.aspx