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, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 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