Calculate the difference between two dates and get the value in years? [duplicate]
Do you want calculate the age in years for an employee? Then you can use this snippet (from Calculate age in C#):
DateTime now = DateTime.Today;
int age = now.Year - bday.Year;
if (bday > now.AddYears(-age)) age--;
If not, then please specify. I'm having a hard time understanding what you want.
Subtracting two DateTime
gives you a TimeSpan
back. Unfortunately, the largest unit it gives you back is Days.
While not exact, you can estimate it, like this:
int days = (DateTime.Today - DOB).Days;
//assume 365.25 days per year
decimal years = days / 365.25m;
Edit: Whoops, TotalDays is a double, Days is an int.
On this site they have:
public static int CalculateAge(DateTime BirthDate)
{
int YearsPassed = DateTime.Now.Year - BirthDate.Year;
// Are we before the birth date this year? If so subtract one year from the mix
if (DateTime.Now.Month < BirthDate.Month || (DateTime.Now.Month == BirthDate.Month && DateTime.Now.Day < BirthDate.Day))
{
YearsPassed--;
}
return YearsPassed;
}
private static Int32 CalculateAge(DateTime DOB)
{
DateTime temp = DOB;
Int32 age = 0;
while ((temp = temp.AddYears(1)) < DateTime.Now)
age++;
return age;
}