Skip to content

Instantly share code, notes, and snippets.

@yeica
Created November 3, 2021 18:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yeica/efa6a474a6990e33f7ce86e742115c3d to your computer and use it in GitHub Desktop.
Save yeica/efa6a474a6990e33f7ce86e742115c3d to your computer and use it in GitHub Desktop.
calculate age with DateTime birthday C#
using System;
public class Program
{
public static void Main()
{
DateTime[] birthdays = new DateTime[]
{
new DateTime(1995, 12, 14),
new DateTime(2001, 1, 21),
new DateTime(1976, 6, 4),
new DateTime(2009, 2, 28)
};
Array.ForEach(birthdays, b => Console.WriteLine(GetAgeByDate(b)));
}
public static int GetAgeByDate(DateTime birthday)
{
return Convert.ToInt16(Math.Truncate((DateTime.Today - birthday).TotalDays / 365.25));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment