How to calculate age based on a DateTime type birthday date in C#

3 Answers

0 votes
using System;

class Program
{
    static void Main() {
        var birthdate = new DateTime(1974, 3, 19);
        var today = DateTime.Today;
        
        int age = today.Year - birthdate.Year;

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

        Console.Write(age);
    }
}



 
/*
run:
 
49   
 
*/

 



answered Jun 7, 2023 by avibootz
0 votes
using System;

class Program
{
    static void Main() {
        var birthdate = new DateTime(1974, 3, 19);
        
        int now = int.Parse(DateTime.Now.ToString("yyyyMMdd"));
        int bd = int.Parse(birthdate.ToString("yyyyMMdd"));
        
        int age = (now - bd) / 10000;
        
        Console.Write(age);
    }
}



 
/*
run:
 
49   
 
*/

 



answered Jun 7, 2023 by avibootz
0 votes
using System;

class Program
{
    static void Main() {
        var birthdate = new DateTime(1974, 3, 19);

        int age = (int) ((DateTime.Now - birthdate).TotalDays / 365);
        
        Console.Write(age);
    }
}



 
/*
run:
 
49   
 
*/

 



answered Jun 7, 2023 by avibootz
...