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


当前回答

MSDN帮助为什么没有告诉您这一点?看起来很明显:

System.DateTime birthTime = AskTheUser(myUser); // :-)
System.DateTime now = System.DateTime.Now;
System.TimeSpan age = now - birthTime; // As simple as that
double ageInDays = age.TotalDays; // Will you convert to whatever you want yourself?

其他回答

我使用这个:

public static class DateTimeExtensions
{
    public static int Age(this DateTime birthDate)
    {
        return Age(birthDate, DateTime.Now);
    }

    public static int Age(this DateTime birthDate, DateTime offsetDate)
    {
        int result=0;
        result = offsetDate.Year - birthDate.Year;

        if (offsetDate.DayOfYear < birthDate.DayOfYear)
        {
              result--;
        }

        return result;
    }
}

SQL版本:

declare @dd smalldatetime = '1980-04-01'
declare @age int = YEAR(GETDATE())-YEAR(@dd)
if (@dd> DATEADD(YYYY, -@age, GETDATE())) set @age = @age -1

print @age  

这是一个非常简单的方法:

int Age = DateTime.Today.Year - new DateTime(2000, 1, 1).Year;

简单易读,方法互补

public static int getAge(DateTime birthDate)
{
    var today = DateTime.Today;
    var age = today.Year - birthDate.Year;
    var monthDiff = today.Month - birthDate.Month;
    var dayDiff = today.Day - birthDate.Day;

    if (dayDiff < 0)
    {
        monthDiff--;
    }
    if (monthDiff < 0)
    {
       age--;
    }
    return age;
}

人们可以这样计算“年龄”(即“西方人”的方式):

public static int AgeInYears(this System.DateTime source, System.DateTime target)
  => target.Year - source.Year is int age && age > 0 && source.AddYears(age) > target ? age - 1 : age < 0 && source.AddYears(age) < target ? age + 1 : age;

如果时间方向为“负”,则年龄也将为负。

可以添加一个分数,代表从目标到下一个生日的累计年龄:

public static double AgeInTotalYears(this System.DateTime source, System.DateTime target)
{
  var sign = (source <= target ? 1 : -1);

  var ageInYears = AgeInYears(source, target); // The method above.

  var last = source.AddYears(ageInYears);
  var next = source.AddYears(ageInYears + sign);

  var fractionalAge = (double)(target - last).Ticks / (double)(next - last).Ticks * sign;

  return ageInYears + fractionalAge;
}

分数是过去的时间(从上一个生日到下一个生日)与总时间的比率。

无论是向前还是向后,这两种方法都以相同的方式工作。