# Calculate age from date of birth

Hi
Just asked this question before and answered points but realised I needed another solution.

I want to calculate a persons age by passing in the date of birth - however the date of birth is a nullable type.              DateTime?

I am using linq to sql and want a method to calculate the age taking into account the nullable date of birth.

So something like

Age = db.CalculatePersonsAge(DOB)

Age is an integer and DOB is nullable
Asked:
###### Who is Participating?

Commented:
Just replace -1 with required age if dob is null
``````public int CalculatePersonsAge (DateTime? dob)
{
return (dob == null) ? -1 : DateTime.Now.AddYears(-1 * ((DateTime)dob).Year).Year;
}
``````
0

Commented:

``````DateTime? birthDate = null;

birthDate = new DateTime(1965, 5, 1);
var age = (birthDate == null) ? -1: DateTime.Now.AddYears(-1*((DateTime)birthDate).Year).Year;
``````
0

Commented:
Is this working for you ?
0

Commented:
Small example
``````private void Form1_Load(object sender, EventArgs e)
{
DateTime? dob = null;
int age;
age = CalculateAge(dob);

age = CalculateAge(new DateTime(1979,02,11));

}

private int CalculateAge(DateTime? dob)
{
if (dob == null)
return -1;

int years = DateTime.Today.Year - ((DateTime)dob).Year;
int months = DateTime.Today.Month - ((DateTime)dob).Month;
int days = DateTime.Today.Day - ((DateTime)dob).Day;

DateTime birthDayThisYear = new DateTime(System.DateTime.Now.Year,((DateTime)dob).Month,((DateTime)dob).Day);

if(birthDayThisYear > DateTime.Today)//you've not yet celebrated your birthday this year
{
years -= 1;
months += 12;
}
if(birthDayThisYear.Day > DateTime.Today.Day)
{
months -= 1;
}
return years;
}
``````
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

## Already a member? Login.

All Courses

From novice to tech pro — start learning today.