给定代表某人生日的DateTime,我如何计算他们的年龄(以年为单位)?


当前回答

另一个功能,不是我做的,而是在网上找到的,并做了一些改进:

public static int GetAge(DateTime birthDate)
{
    DateTime n = DateTime.Now; // To avoid a race condition around midnight
    int age = n.Year - birthDate.Year;

    if (n.Month < birthDate.Month || (n.Month == birthDate.Month && n.Day < birthDate.Day))
        age--;

    return age;
}

我只想到了两件事:来自不使用公历的国家的人呢?DateTime。我认为现在是服务器特定的文化。我对实际使用亚洲日历一无所知,我不知道是否有一种简单的方法来转换日历之间的日期,但以防万一,你想知道4660年的中国人:-)

其他回答

int Age = new DateTime((DateTime.Now - BirthDate).Ticks).Year -1;
Console.WriteLine("Age {0}", Age);

我强烈建议使用名为AgeCalculator的NuGet软件包,因为在计算年龄(闰年、时间成分等)时需要考虑很多事情,而且只有两行代码不能削减它。该库给您的时间不只是一年。它甚至在计算时考虑了时间成分,这样你就可以得到一个包含年、月、日和时间成分的准确年龄。更为先进的是,可以选择将2月29日作为闰年,而将2月28日作为非闰年。

我经常用手指数。我需要看一下日历,以确定事情何时发生变化。这就是我在代码中要做的:

int AgeNow(DateTime birthday)
{
    return AgeAt(DateTime.Now, birthday);
}

int AgeAt(DateTime now, DateTime birthday)
{
    return AgeAt(now, birthday, CultureInfo.CurrentCulture.Calendar);
}

int AgeAt(DateTime now, DateTime birthday, Calendar calendar)
{
    // My age has increased on the morning of my
    // birthday even though I was born in the evening.
    now = now.Date;
    birthday = birthday.Date;

    var age = 0;
    if (now <= birthday) return age; // I am zero now if I am to be born tomorrow.

    while (calendar.AddYears(birthday, age + 1) <= now)
    {
        age++;
    }
    return age;
}

在LINQPad中运行此过程可获得以下结果:

PASSED: someone born on 28 February 1964 is age 4 on 28 February 1968
PASSED: someone born on 29 February 1964 is age 3 on 28 February 1968
PASSED: someone born on 31 December 2016 is age 0 on 01 January 2017

LINQPad中的代码在这里。

这里有一个非常简单且易于遵循的示例。

private int CalculateAge()
{
//get birthdate
   DateTime dtBirth = Convert.ToDateTime(BirthDatePicker.Value);
   int byear = dtBirth.Year;
   int bmonth = dtBirth.Month;
   int bday = dtBirth.Day;
   DateTime dtToday = DateTime.Now;
   int tYear = dtToday.Year;
   int tmonth = dtToday.Month;
   int tday = dtToday.Day;
   int age = tYear - byear;
   if (bmonth < tmonth)
       age--;
   else if (bmonth == tmonth && bday>tday)
   {
       age--;
   }
return age;
}

不知道为什么没有人尝试过:

        ushort age = (ushort)DateAndTime.DateDiff(DateInterval.Year, DateTime.Now.Date, birthdate);

它只需要使用Microsoft.VisualBasic;并引用项目中的此程序集(如果尚未引用)。