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

时间:2010-06-30 20:05:31

标签: c# datetime timespan

  

可能重复:
  How do I calculate someone’s age in C#?

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

int age=Convert.Int32(DateTime.Now-DOB);

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

6 个答案:

答案 0 :(得分:77)

您想要计算员工的年龄吗?然后,您可以使用此代码段(来自Calculate age in C#):

DateTime now = DateTime.Today;
int age = now.Year - bday.Year;
if (bday > now.AddYears(-age)) age--;

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

答案 1 :(得分:16)

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

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

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

//assume 365.25 days per year
decimal years = days / 365.25m;

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

答案 2 :(得分:7)

this网站上,他们有:

   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;
  }

答案 3 :(得分:4)

    private static Int32 CalculateAge(DateTime DOB)
    {
        DateTime temp = DOB;
        Int32 age = 0;
        while ((temp = temp.AddYears(1)) < DateTime.Now)
            age++;
        return age;
    }

答案 4 :(得分:0)

Math.Round(DateTime.Now.Subtract(DOB).TotalDays / 365.0)

正如所指出的,这不起作用。你必须这样做:

(Int32)Math.Round((span.TotalDays - (span.TotalDays % 365.0)) / 365.0);

并且在那时,另一个解决方案不那么复杂,并且在更大的跨度上继续保持准确。

编辑2,怎么样:

Math.Floor(DateTime.Now.Subtract(DOB).TotalDays/365.0)

基督我这些天吮吸基础数学......

答案 5 :(得分:-4)

(DateTime.Now - DOB).TotalDays/365

从另一个DateTime结构中减去DateTime结构将为您提供一个TimeSpan结构,其具有属性TotalDays ...然后除以365

相关问题