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
Tweet
1 comment:
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
Post a Comment