Click here to Skip to main content
15,889,889 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,

I have nullable Datetime and I cannot calculate age. Please help.
public static int GetPersonAge(DateTime? birthDay, DateTime endDate)
{
    int years = endDate.Year - birthDay.Year;

    if (birthDay.Month > endDate.Month || (birthDay.Month == endDate.Month && 
      birthDay.Day > endDate.Day))
      years--;
            
      return years;
}


Thanks

What I have tried:

Stackoverfllow, MSD Forum
Posted
Updated 8-Jul-19 20:47pm

birthDay is a Nullable<DateTime>, so it doesn't have .Year, .Month, etc. The value of the nullable - if there is any - does. So either change your method to accept a DateTime rather than a nullable, or extract the birthDay value before using it (if there is a value - you can check this with .HasValue. If there is no value, do whatever you want to do).
 
Share this answer
 
Use

birthDay.Value.Year


rather than

birthDay.Year


Same with Month etc. Your code also needs to handle for when birthDay is null so you need to decide what happens in that scenario. You can use

if (!birthDay.HasValue)
{
    // ....
}


to check.
 
Share this answer
 
In addition to using the HasValue and Value properties that have been suggested, you may find this useful: Working with Age: it's not the same as a TimeSpan![^]
 
Share this answer
 
Similar to the solutions provided above, first check if the birthday is null and then access the value and then year/month/day.

public static int GetPersonAge(DateTime? birthDay, DateTime endDate)
        {

            if (birthDay == null)
            {
                throw new ArgumentNullException($"Cannot calculate Age"); 
            }
            
            int years = endDate.Year - birthDay.Value.Year;

            if (birthDay.Value.Month > endDate.Month || (birthDay.Value.Month == endDate.Month &&
                                                   birthDay.Value.Day > endDate.Day))
                years--;

            return years;
        }
 
Share this answer
 
v2
Ideally, you should return nullable int to handle null date of birth.
Return null if birthDay is null because in that case, you can't calculate the age.

C#
public static int? GetPersonAge(DateTime? birthDay, DateTime endDate)
	{
		if(birthDay.HasValue)
		{
			int years = endDate.Year - birthDay.Value.Year;

			if (birthDay.Value.Month > endDate.Month || (birthDay.Value.Month == endDate.Month && birthDay.Value.Day > endDate.Day))
		  		years--;

		  	return years;
		}
		return null;		
	}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900