This code snippet can help you to calculate a Person’s age using C# and VB.NET.
C# Snippet
#region using System; #endregion namespace de.Fesslersoft.CalculateAge { internal class Program { public static int CalculateAge(DateTime birthday) { var todaysDate = DateTime.Today; var ageCalculated = todaysDate.Year - birthday.Year; if (birthday > todaysDate.AddYears(-ageCalculated)) { ageCalculated = ageCalculated - 1; } return ageCalculated; } private static void Main(string[] args) { var myBirthday = new DateTime(1982, 3, 22); var age = CalculateAge(myBirthday); Console.WriteLine("Calculated age is {0}", age); Console.ReadLine(); } } }
VB.NET Snippet
Namespace de.Fesslersoft.CalculateAge Module Module1 Sub Main() Dim myBirthday = New DateTime(1982, 3, 22) Dim age = CalculateAge(myBirthday) Console.WriteLine("Calculated age is {0}", age) Console.ReadLine() End Sub Public Function CalculateAge(birthday As DateTime) As Integer Dim todaysDate = DateTime.Today Dim ageCalculated = todaysDate.Year - birthday.Year If birthday > todaysDate.AddYears(- ageCalculated) Then ageCalculated = ageCalculated - 1 End If Return ageCalculated End Function End Module End Namespace
If you have any questions or suggestions feel free to rate this snippet, post a comment or Contact Us via Email.
Related links: DateTime Structure, DateTime Methods