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


当前回答

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

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中的代码在这里。

其他回答

这里有一个单行线:

int age = new DateTime(DateTime.Now.Subtract(birthday).Ticks).Year-1;

哇,我不得不在这里回答。。。这么简单的问题有很多答案。

private int CalcularIdade(DateTime dtNascimento)
    {
        var nHoje = Convert.ToInt32(DateTime.Today.ToString("yyyyMMdd"));
        var nAniversario = Convert.ToInt32(dtNascimento.ToString("yyyyMMdd"));

        double diff = (nHoje - nAniversario) / 10000;

        var ret = Convert.ToInt32(Math.Truncate(diff));

        return ret;
    }

无分支解决方案:

public int GetAge(DateOnly birthDate, DateOnly today)
{
    return today.Year - birthDate.Year + (((today.Month << 5) + today.Day - ((birthDate.Month << 5) + birthDate.Day)) >> 31);
}

一句话的回答:

DateTime dateOfBirth = Convert.ToDateTime("01/16/1990");
var age = ((DateTime.Now - dateOfBirth).Days) / 365;

为了计算一个人的年龄,

DateTime dateOfBirth;

int ageInYears = DateTime.Now.Year - dateOfBirth.Year;

if (dateOfBirth > today.AddYears(-ageInYears )) ageInYears --;