Calculate age from DateTime?

Jassim Al Rahma 1,616 Reputation points
2022-12-21T22:19:14.94+00:00

Hi,

I am trying:

int age = DateTime.Today.Subtract(DXDateOfBirth.Date);  

but getting this error:

Argument 1: cannot convert from 'System.DateTime?' to 'System.DateTime'

Kindly help..

Thanks,
Jassim

Developer technologies | C#
0 comments No comments
{count} votes

Accepted answer
  1. Michael Taylor 60,161 Reputation points
    2022-12-21T22:28:10.493+00:00

    DXDateOfBirth.Date is typed as DateTime? or a nullable datetime. If you are sure this is always a valid date then use the .GetValueOrDefault() method.

       int age = DateTime.Today.Subtract(DXDateOfBirth.Date.GetValueOrDefault());  
    

    If you might not actually have a date then you should first check to see if it is set.

       int age = DXDateOfBirth.Date.HasValue ? DateTime.Today.Subtract(DXDateOfBirth.Date.Value) : 0;  
    

1 additional answer

Sort by: Most helpful
  1. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2022-12-27T16:58:29.17+00:00

    Here is something to try adapted from this code.

    public static class Extensions  
    {  
        public static int Age(this DateTime? sender)  
        {  
            if (sender.HasValue)  
            {  
                var today = DateTime.Today;  
                var age = today.Year - sender.Value.Year;  
                if (sender.Value.Date > today.AddYears(-age)) age--;  
                return age;  
            }  
            else  
            {  
                return 0;  
            }  
        }  
    }  
    

    In a console project

    static void Main(string[] args)  
    {  
        DateTime? birthdate = new DateTime(1956, 9, 24);  
        Console.WriteLine(birthdate.Age());  
        Console.ReadLine();  
    }  
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.