How to Calculate age from Date of Birth (DOB)

edx
edx
58 Points
19 Posts

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

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

Share:   fb twitter linkedin
Answers
beginer
beginer
100 Points
35 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
Member
114 Points
27 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
Member
366 Points
153 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
 Log In to Chat