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#.
using System;
public class HelloWorld
{
    public static void Main(string[] args)
    {
        DateTime birthdate = DateTime.ParseExact("1989-02-25", "yyyy-MM-dd",                                               System.Globalization.CultureInfo.InvariantCulture);
        var today = DateTime.Today;
        
        var age = today.Year - birthdate.Year;
        
        today.AddYears(-age);
        
        Console.WriteLine (age);
    }
}

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