jQuery and ASP.NET

December 25, 2009

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


Bookmark this link on del.icio.us (saved by 0 users)

Did you like this post?
kick it on DotNetKicks.com
subscribe via rss subscribe via e-mail
print this post follow me on twitter
Others Also Read..

comments

0 Responses to "Calculate Age in Years using C# or VB.NET"
 

Copyright 2010 All Rights Reserved DevCurry.com by Suprotim Agarwal