Possible Duplicate:
How do I calculate someone’s age in C#?
I want to calculate basically the age of employees - So we have DOB for each employee, So on the C# Side I want to do something like this开发者_高级运维 -
int age=Convert.Int32(DateTime.Now-DOB);
I can use days and manipulate then get the age...but I wanted to know if there something I can use directly to get the number of years.
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;
}
Math.Round(DateTime.Now.Subtract(DOB).TotalDays/365.0)
As pointed out, this won't work. You'd have to do this:
(Int32)Math.Round((span.TotalDays - (span.TotalDays % 365.0)) / 365.0);
and at that point the other solution is less complex and continues to be accurate over larger spans.
Edit 2, how about:
Math.Floor(DateTime.Now.Subtract(DOB).TotalDays/365.0)
Christ I suck at basic math these days...
(DateTime.Now - DOB).TotalDays/365
Subtracting a DateTime struct from another DateTime struct will give you a TimeSpan struct which has the property TotalDays... then just divide by 365
精彩评论