Wednesday, April 6, 2022

How to calculate Age based on a birthday in C#

Here is a sample code to calculate Age based on a birthday in C#.
  1. using System;
  1. public class HelloWorld
  2. {
  3. public static void Main(string[] args)
  4. {
  5. DateTime birthdate = DateTime.ParseExact("1989-02-25", "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
  6. var today = DateTime.Today;
  7. var age = today.Year - birthdate.Year;
  8. today.AddYears(-age);
  9. Console.WriteLine (age);
  10. }
  11. }

1 comment:

  1. I'd do this:

    var today = DateTime.Today;

    var age = today.Year - birthdate.Year;

    if (birthdate.Date > today.AddYears(-age))
    age--;

    ReplyDelete