Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,938 questions

51,875 answers

573 users

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
...