How to Calculate age from Date of Birth (DOB)

edx
edx
506 Points
24 Posts

I have user's birthday in datatime object format, how do I calculate their age in years?

Views: 9717
Total Answered: 4
Total Marked As Answer: 0
Posted On: 27-Mar-2019 02:45

Share:   fb twitter linkedin
Answers
beginer
beginer
1544 Points
52 Posts
         

You can try easy and simple way:

var today = DateTime.Today;
// Calculate the age.
var age = today.Year - birthdate.Year;
// Go back to the year the person was born in case of a leap year
if (birthdate > today.AddYears(-age)) age--;
Posted On: 30-Mar-2019 00:25
Rashmi
Rashmi
1068 Points
19 Posts
         

Use following code:

private static int CalculateAgeFromDateObject(DateTime dateOfBirth)  
{  
    int age = 0;  
    age = DateTime.Now.Year - dateOfBirth.Year;  
    if (DateTime.Now.DayOfYear < dateOfBirth.DayOfYear)  
        age = age - 1;  
  
    return age;  
}  
Posted On: 30-Mar-2019 00:28
Jak
Jak
908 Points
132 Posts
         

Here is another solution to calculate the years, months and days for given date of birth:

DateTime dateOfBirth = new DateTime(1990, 3, 11);
DateTime currentDate = DateTime.Now;

int ageInYears = 0;
int ageInMonths = 0;
int ageInDays = 0;

ageInDays = currentDate.Day - dateOfBirth.Day;
ageInMonths = currentDate.Month - dateOfBirth.Month;
ageInYears = currentDate.Year - dateOfBirth.Year;

if (ageInDays < 0)
{
    ageInDays += DateTime.DaysInMonth(currentDate.Year, currentDate.Month);
    ageInMonths = ageInMonths--;

    if (ageInMonths < 0)
    {
        ageInMonths += 12;
        ageInYears--;
    }
}

if (ageInMonths < 0)
{
    ageInMonths += 12;
    ageInYears--;
}

Console.WriteLine("{0} years, {1} months, {2} days",
ageInYears, ageInMonths, ageInDays);
Posted On: 02-Apr-2019 07:33
edx
edx
506 Points
24 Posts
         

Here is one more method to calculate the age by considering the leap year:

public int CalculateAge(DateTime dob)
{
    int age = 0, dayofyr = 0;

    if (DateTime.IsLeapYear(dob.Year) && dob.DayOfYear >= 60)
        dayofyr = dob.DayOfYear - 1;
    else
        dayofyr = dob.DayOfYear;

    age = DateTime.Now.Year - dob.Year;

    if (DateTime.Now.DayOfYear < dayofyr)
        age--;

    return age;
}

 

Posted On: 07-Sep-2021 02:52
 Log In to Chat