Calculate the difference between two dates and get the value in years? [duplicate]

穿精又带淫゛_ 提交于 2019-11-28 09:35:18
alexn

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!