计算两个日期之间的差异并获得多年的价值?

Vis*_*hal 44 c# datetime timespan

可能重复:
如何计算C#中某人的年龄?

我想基本计算员工的年龄 - 所以我们每个员工都有DOB,所以在C#方面我想做这样的事情 -

int age=Convert.Int32(DateTime.Now-DOB);
Run Code Online (Sandbox Code Playgroud)

我可以使用天和操纵然后获得年龄...但我想知道是否有我可以直接使用的东西来获得年数.

ale*_*exn 82

您想要计算员工的年龄吗?然后你可以使用这个片段(来自C#中的计算年龄):

DateTime now = DateTime.Today;
int age = now.Year - bday.Year;
if (bday > now.AddYears(-age)) age--;
Run Code Online (Sandbox Code Playgroud)

如果没有,请说明.我很难理解你想要的东西.


Pow*_*ord 17

减去两个DateTime会给你一个TimeSpan回报.不幸的是,它给你的最大单位是Days.

虽然不准确,但您可以估算它,如下所示:

int days = (DateTime.Today - DOB).Days;

//assume 365.25 days per year
decimal years = days / 365.25m;
Run Code Online (Sandbox Code Playgroud)

编辑:哎呀,TotalDays是双倍,Days是int.

  • .25是由于闰年 (4认同)
  • @ matt-dot-net由于唯一重要的时间是115岁以上的人,我相信它在大多数情况下都会起作用. (4认同)

Kyr*_*yra 7

这个网站上他们有:

   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;
  }
Run Code Online (Sandbox Code Playgroud)