如何计算C#中某人的年龄?

Jeff Atwood 1743 .net c# datetime

鉴于DateTime代表一个人的生日,我如何计算他们的年龄?

Mike Polen.. 1860

一个易于理解和简单的解决方案.

// Save today's date.
var today = DateTime.Today;
// Calculate the age.
var age = today.Year - birthdate.Year;
// Go back to the year the person was born in case of a leap year
if (birthdate > today.AddYears(-age)) age--;

然而,这假设您正在寻找西方的年龄观念,而不是使用东亚推算.

  • 只是想对DateTime.Now性能发表评论.如果您不需要准确的时区值,请使用DateTime.UtcNow它更快. (220认同)
  • 最后一行让我想得太多了.相反如何:if(bday.AddYears(age)> now)age--; 这似乎是一个更直观的表达. (98认同)
  • 鉴于我们正在谈论生日,你可以使用DateTime.Today给定时间部分没有相关性. (92认同)
  • 此答案不适用于所有语言环境和所有年龄段.一些国家在现有生活者出生后跳过了日期,包括俄罗斯(1918年),希腊(1924年)和土耳其(1926年). (73认同)
  • 实际上,它仍然不完全正确.此代码假定'bday'是DateTime的日期部分.这是一个边缘情况(我想大多数人只会传递日期而不是日期时间),但是如果你过了一个生日作为时间大于00:00:00的日期和时间那么你'我会遇到Danvil指出的bug.设置bday = bday.Date解决了这个问题. (27认同)
  • 好主意cdiggins,但它不能作为bday.AddYears(年龄)当年龄是2/29时返回2/28岁的年份不是闰年...继续尝试 (11认同)
  • @NKCSS:这不能正确处理闰年.我的测试显示只有`if(bday> now.AddYears(-age))`有效.因为`DayOfYear`在2012年返回'61`,在2011年返回'60`在3月1日. (6认同)
  • @LarsD所以你说的是没有办法计算人的年龄?垃圾.他们搞乱了他们的日历,他们可以适应.即使您可以根据区域设置进行库来计算交叉日历,a)您在哪里获取此信息b)它真的值得吗? (3认同)
  • 快速有趣的事实:这个答案在这个[复数视频课程](https://app.pluralsight.com/library/courses/linq-more-effective/table-of-contents)的第5单元 - 第3章中有所体现. (3认同)
  • 那么根据不同的国家和日历我们有不同的年龄?什么是独家新闻...... (2认同)
  • 是不是更容易做到`DateTime dateDifference = subject.Birthday - DateTime.Now; int age = dateDifference.Year;`?此外,我认为年龄不取决于闰年.毕竟,一年被定义为365 <x <366天,闰年不会让你任何一天更年轻. (2认同)
  • @cja - 这意味着一些国家在几年前做了一些功能来同步日历并消除差异!http://en.wikipedia.org/wiki/Gregorian_calendar可能会更多地谈论它,我还没有完全阅读.对"当前人"的提及仅仅是指出调整发生在20世纪(1901-2000).从那个时期开始,很多人还活着!:) (2认同)
  • _在英格兰和威尔士或香港,2月29日出生的人将在3月1日合法地达到18岁.如果他或她出生在台湾,他或她在2月28日,合法地在18日前一天成为18岁. [维基百科](https://en.wikipedia.org/wiki/February_29#Legal_status))所以`birthdate.AddYears(age)> today`和`birthdate> today.AddYears(-age)`都是正确的和不正确的,取决于司法管辖区. (2认同)
  • 这个解决方案是否超过1400个upvotes是正确的,因为我可以从评论部分读到这个解决方案存在一些问题......? (2认同)

ScArcher2.. 943

这是一种奇怪的方法,但是如果您将日期格式化yyyymmdd为当前日期并从当前日期减去出生日期,则删除您已达到年龄的最后4位数字:)

我不知道C#,但我相信这适用于任何语言.

20080814 - 19800703 = 280111 

删掉最后4位= 28.

C#代码:

int now = int.Parse(DateTime.Now.ToString("yyyyMMdd"));
int dob = int.Parse(dateOfBirth.ToString("yyyyMMdd"));
int age = (now - dob) / 10000;

或者可选地,没有以扩展方法的形式进行所有类型转换.错误检查省略:

public static Int32 GetAge(this DateTime dateOfBirth)
{
    var today = DateTime.Today;

    var a = (today.Year * 100 + today.Month) * 100 + today.Day;
    var b = (dateOfBirth.Year * 100 + dateOfBirth.Month) * 100 + dateOfBirth.Day;

    return (a - b) / 10000;
}

  • Horray为'yyyymmdd`.我在**P**ersonal**C**omputer(大约1981年)上使用的第一个数据库产品以这种格式存储日期.任何类型的日期操作都非常容易. (49认同)
  • 实际上,这非常适合在MS-SQL上使用datetime-fields(自01-011900以来的总天数) (2认同)
  • @numerek请将您建议的修改发布为自己的答案.值得一提的是,当前年份10000不会出现整数溢出,接近两个数量级.20,150,000 vs 2,147,483,648 (2认同)
  • @LongChalk`20180101 - 20171231 = 8870`.丢弃最后4位数字,你有(隐含的)年龄为"0"的数字.你怎么得到`1`? (2认同)

用户甲.. 361

我不知道如何接受错误的解决方案.正确的C#片段由Michael Stum撰写

这是一个测试片段:

DateTime bDay = new DateTime(2000, 2, 29);
DateTime now = new DateTime(2009, 2, 28);
MessageBox.Show(string.Format("Test {0} {1} {2}",
                CalculateAgeWrong1(bDay, now),     // outputs 9
                CalculateAgeWrong2(bDay, now),     // outputs 9
                CalculateAgeCorrect(bDay, now)));  // outputs 8

在这里你有方法:

public int CalculateAgeWrong1(DateTime birthDate, DateTime now)
{
    return new DateTime(now.Subtract(birthDate).Ticks).Year - 1;
}

public int CalculateAgeWrong2(DateTime birthDate, DateTime now)
{
    int age = now.Year - birthDate.Year;

    if (now < birthDate.AddYears(age))
        age--;

    return age;
}

public int CalculateAgeCorrect(DateTime birthDate, DateTime now)
{
    int age = now.Year - birthDate.Year;

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

    return age;
}

  • 虽然这段代码有效,但它断言,闰日出生的人在3月1日非闰年而不是2月28日达到下一年的年龄.实际上,*任一选项都可能是正确的*.[维基百科对此有所说明](http://en.wikipedia.org/wiki/Leap_day#Births).因此,虽然您的代码不是"错误",但也不是可接受的解决方案. (27认同)
  • @MattJohnson我认为这是正确的.如果我的bday是2月29日,那么2月28日我的bday还没有过去,我应该和2月27日的年龄相同.然而,3月1日,我们已经过了我的bday,我应该是下一个年龄.在美国,销售酒精的企业会有一个标志,上面写着"如果您在YYYY之后出生,那么您就不能购买酒精"(YYYY每年都会改变).这意味着2月29日出生的人在他们年满21岁(大多数地方)的那一年不能在2月28日购买酒精,并支持他们在3月1日之前年龄不大的想法. (13认同)
  • 输出为-Test 9 9 8 (8认同)
  • @ jfren484你的主张完全与哲学无关; 但与你自己的个人感觉***有关.当2月29日出生的人"年龄"在很大程度上不重要,除非年龄形成"法定年龄边界"(例如,可以购买酒精,投票,领取养老金,加入军队,获得驾驶执照).考虑美国饮酒年龄(21岁):对于大多数人来说是7670天.如果在闰年2月29日之前或闰年之前的3月1日出生,则为7671天.如果出生于2月29日:2月28日是7670天,3月1日是7671天.***选择是任意的***它可以去任何一种方式. (5认同)
  • @ jfren484 - 阅读维基百科文章.它在各个司法管辖区之间差异很大. (2认同)

James A. Ros.. 125

我认为迄今为止的任何答案都没有提供以不同方式计算年龄的文化.例如,参见东亚年龄估算与西方年龄相比.

任何真正的答案都必须包括本地化.在这个例子中,战略模式可能是有序的.

  • 从您提供的维基百科文章中可以看出:"在中国和日本,它被用于传统的算命或宗教信仰,它在城市人们之间的日常生活中消失了." (24认同)
  • 实际上这个概念非常重要 - 人们不喜欢被错误地告知他们的个人信息.例如,我的一半家庭住在马来西亚,一半住在英国.现在,当我与家人的一方而不是另一方时,我的年龄被认为高出两年. (21认同)
  • @some - 韩国人仍然主要使用这个系统. (7认同)
  • 不仅我们这个系统主要在韩国使用,而且作为一个与当地人讨论年龄的游客,当地人会礼貌地在出生年份之前互相提及自己.我不是25岁,我是87岁.我更喜欢这种方法.更多'国际生日时间格式' (6认同)
  • 在越南,即使使用西方系统,在日常生活中,仅通过减去年数来计算年龄.日期不包括在内 (2认同)

用户甲.. 103

对此的简单回答是应用AddYears如下所示,因为这是闰年2月29日增加年份的唯一本机方法,并获得2月28日的正确年份的正确结果.

有些人认为3月1日是闰人的生日,但是.Net和任何官方规则都不支持这一点,也没有共同逻辑解释为什么2月份出生的人应该在另一个月有75%的生日.

此外,Age方法适合作为扩展添加DateTime.通过这种方式,您可以以最简单的方式获得年龄:

  1. 项目清单

int age = birthDate.Age();

public static class DateTimeExtensions
{
    /// <summary>
    /// Calculates the age in years of the current System.DateTime object today.
    /// </summary>
    /// <param name="birthDate">The date of birth</param>
    /// <returns>Age in years today. 0 is returned for a future date of birth.</returns>
    public static int Age(this DateTime birthDate)
    {
        return Age(birthDate, DateTime.Today);
    }

    /// <summary>
    /// Calculates the age in years of the current System.DateTime object on a later date.
    /// </summary>
    /// <param name="birthDate">The date of birth</param>
    /// <param name="laterDate">The date on which to calculate the age.</param>
    /// <returns>Age in years on a later day. 0 is returned as minimum.</returns>
    public static int Age(this DateTime birthDate, DateTime laterDate)
    {
        int age;
        age = laterDate.Year - birthDate.Year;

        if (age > 0)
        {
            age -= Convert.ToInt32(laterDate.Date < birthDate.Date.AddYears(age));
        }
        else
        {
            age = 0;
        }

        return age;
    }
}

现在,运行此测试:

class Program
{
    static void Main(string[] args)
    {
        RunTest();
    }

    private static void RunTest()
    {
        DateTime birthDate = new DateTime(2000, 2, 28);
        DateTime laterDate = new DateTime(2011, 2, 27);
        string iso = "yyyy-MM-dd";

        for (int i = 0; i < 3; i++)
        {
            for (int j = 0; j < 3; j++)
            {
                Console.WriteLine("Birth date: " + birthDate.AddDays(i).ToString(iso) + "  Later date: " + laterDate.AddDays(j).ToString(iso) + "  Age: " + birthDate.AddDays(i).Age(laterDate.AddDays(j)).ToString());
            }
        }

        Console.ReadKey();
    }
}

关键日期的例子如下:

出生日期:2000-02-29后期:2011-02-28年龄:11岁

输出:

{
    Birth date: 2000-02-28  Later date: 2011-02-27  Age: 10
    Birth date: 2000-02-28  Later date: 2011-02-28  Age: 11
    Birth date: 2000-02-28  Later date: 2011-03-01  Age: 11
    Birth date: 2000-02-29  Later date: 2011-02-27  Age: 10
    Birth date: 2000-02-29  Later date: 2011-02-28  Age: 11
    Birth date: 2000-02-29  Later date: 2011-03-01  Age: 11
    Birth date: 2000-03-01  Later date: 2011-02-27  Age: 10
    Birth date: 2000-03-01  Later date: 2011-02-28  Age: 10
    Birth date: 2000-03-01  Later date: 2011-03-01  Age: 11
}

而对于2012-02-28的后期日期:

{
    Birth date: 2000-02-28  Later date: 2012-02-28  Age: 12
    Birth date: 2000-02-28  Later date: 2012-02-29  Age: 12
    Birth date: 2000-02-28  Later date: 2012-03-01  Age: 12
    Birth date: 2000-02-29  Later date: 2012-02-28  Age: 11
    Birth date: 2000-02-29  Later date: 2012-02-29  Age: 12
    Birth date: 2000-02-29  Later date: 2012-03-01  Age: 12
    Birth date: 2000-03-01  Later date: 2012-02-28  Age: 11
    Birth date: 2000-03-01  Later date: 2012-02-29  Age: 11
    Birth date: 2000-03-01  Later date: 2012-03-01  Age: 12
}

  • 关于2月29日生日3月1日的评论,从技术上讲,在28日举行是太早了(事实上提前1天).一日是太晚了一天.但是由于生日介于两者之间,使用第一个来计算非闰年的年龄对我来说更有意义,因为那个人确实在每年的3月1日(以及第2和第3年),但不是2月28日. (3认同)

James Curran.. 79

我的建议

int age = (int) ((DateTime.Now - bday).TotalDays/365.242199);

这似乎在正确的日期改变了一年.(我发现测试到107岁)

  • 我不认为Harry Patch会赞赏你的现场测试方法:http://www.latimes.com/news/obituaries/la-me-harry-patch26-2009jul26,0,7608030.story (22认同)
  • 一年365天.闰年+0.25.其他更正为+0.005 (13认同)
  • ^^因为有时它很重要.在我的测试中,这个人在生日那天失败了,它报告说他们比他们年轻. (11认同)
  • 格里高利历中一年的平均长度为365.2425天. (10认同)
  • 365.255来自哪里?我认为这不会起作用. (4认同)
  • 我会说,这是最简单的解决方案之一,它足够*.谁在乎我是否在我的Xth生日前半天,并且程序说我已经X岁了.该程序或多或少是正确的,尽管不是数学上的.我非常喜欢这个解决方案. (4认同)

Michael Stum.. 69

另一个功能,不是我,而是在网上找到并稍微改进一下:

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.Now是我认为的特定于服务器的文化.我对亚洲日历的实际工作知之甚少,我不知道是否有一种简单的方法可以在日历之间转换日期,但万一你想知道那些来自4660年的中国人:-)


Thetam.. 47

2要解决的主要问题是:

1.计算确切年龄 - 以年,月,日等为单位.

2.计算一般认知的年龄 - 人们通常不关心他们到底多大年纪,他们只关心当年的生日.


1的解决方案很明显:

DateTime birth = DateTime.Parse("1.1.2000");
DateTime today = DateTime.Today;     //we usually don't care about birth time
TimeSpan age = today - birth;        //.NET FCL should guarantee this as precise
double ageInDays = age.TotalDays;    //total number of days ... also precise
double daysInYear = 365.2425;        //statistical value for 400 years
double ageInYears = ageInDays / daysInYear;  //can be shifted ... not so precise

2的解决方案是在确定总年龄时不那么精确的解决方案,但被人们认为是精确的.当人们"手动"计算他们的年龄时,人们通常也会使用它:

DateTime birth = DateTime.Parse("1.1.2000");
DateTime today = DateTime.Today;
int age = today.Year - birth.Year;    //people perceive their age in years

if (today.Month < birth.Month ||
   ((today.Month == birth.Month) && (today.Day < birth.Day)))
{
  age--;  //birthday in current year not yet reached, we are 1 year younger ;)
          //+ no birthday for 29.2. guys ... sorry, just wrong date for birth
}

2的注释:

  • 这是我的首选解决方案
  • 我们不能使用DateTime.DayOfYear或TimeSpans,因为它们会改变闰年的天数
  • 为了便于阅读,我已经添加了更多的行

再说一遍......我会为它创建2个静态重载方法,一个用于通用,第二个用于友好性:

public static int GetAge(DateTime bithDay, DateTime today) 
{ 
  //chosen solution method body
}

public static int GetAge(DateTime birthDay) 
{ 
  return GetAge(birthDay, DateTime.Now);
}


SillyMonkey.. 45

我迟到了,但这是一个单行:

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

  • 这已破了.make testable:public static int CalculateAge(DateTime dateOfBirth,DateTime dateToCalculateAge){return new DateTime(dateToCalculateAge.Subtract(dateOfBirth).Ticks).Year - 1; 当我输入1990-06-01并计算他14岁生日(1990-05-31)之前的年龄时给出14岁. (22认同)

David Wengie.. 36

这是我们在这里使用的版本.它有效,而且非常简单.它与杰夫的想法相同,但我认为它更清晰一点,因为它分离出减去逻辑的逻辑,所以它更容易理解.

public static int GetAge(this DateTime dateOfBirth, DateTime dateAsAt)
{
    return dateAsAt.Year - dateOfBirth.Year - (dateOfBirth.DayOfYear < dateAsAt.DayOfYear ? 0 : 1);
}

如果您认为有些事情不清楚,您可以扩展三元运算符以使其更清晰.

显然这是作为一种扩展方法完成的DateTime,但显然你可以抓住那一行代码完成工作并把它放在任何地方.这里我们有另一个传入的Extension方法的重载DateTime.Now,只是为了完整性.

  • 我认为,当dateOfBirth或dateAsAt中的一个完全属于闰年时,可能会有一天关闭.考虑一下在2003年3月1日出生于2004年2月29日的人的年龄.为了纠正这个问题,你需要对(月,日)月对进行字典比较并将其用于条件. (5认同)

Nick Berardi.. 32

我知道的最好的方法是因为闰年和一切都是:

DateTime birthDate = new DateTime(2000,3,1);
int age = (int)Math.Floor((DateTime.Now - birthDate).TotalDays / 365.25D);

希望这可以帮助.


Elmer.. 30

我用这个:

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


用户甲.. 29

这为这个问题提供了"更多细节".也许这就是你要找的东西

DateTime birth = new DateTime(1974, 8, 29);
DateTime today = DateTime.Now;
TimeSpan span = today - birth;
DateTime age = DateTime.MinValue + span;

// Make adjustment due to MinValue equalling 1/1/1
int years = age.Year - 1;
int months = age.Month - 1;
int days = age.Day - 1;

// Print out not only how many years old they are but give months and days as well
Console.Write("{0} years, {1} months, {2} days", years, months, days);

  • 你是对的不是.但如果这是结果.为什么这有关系?它没有.在任何一种情况下跳跃或没有,那么有一些例子,这是行不通的.这就是我想展示的.DIFF是正确的.Span考虑了闰年.但是添加到基准日期不是.尝试代码中的示例,你会发现我是对的. (3认同)

user2601.. 24

我创建了一个SQL Server用户定义函数来计算某人的年龄,考虑到他们的出生日期.当您需要它作为查询的一部分时,这非常有用:

using System;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;

public partial class UserDefinedFunctions
{
    [SqlFunction(DataAccess = DataAccessKind.Read)]
    public static SqlInt32 CalculateAge(string strBirthDate)
    {
        DateTime dtBirthDate = new DateTime();
        dtBirthDate = Convert.ToDateTime(strBirthDate);
        DateTime dtToday = DateTime.Now;

        // get the difference in years
        int years = dtToday.Year - dtBirthDate.Year;

        // subtract another year if we're before the
        // birth day in the current year
        if (dtToday.Month < dtBirthDate.Month || (dtToday.Month == dtBirthDate.Month && dtToday.Day < dtBirthDate.Day))
            years=years-1;

        int intCustomerAge = years;
        return intCustomerAge;
    }
};


用户甲.. 22

我花了一些时间研究这个并想出了这个来计算一个人的年龄,数月和数日.我已经对2月29日的问题和闰年进行了测试,似乎有效,我很感激任何反馈:

public void LoopAge(DateTime myDOB, DateTime FutureDate)
{
    int years = 0;
    int months = 0;
    int days = 0;

    DateTime tmpMyDOB = new DateTime(myDOB.Year, myDOB.Month, 1);

    DateTime tmpFutureDate = new DateTime(FutureDate.Year, FutureDate.Month, 1);

    while (tmpMyDOB.AddYears(years).AddMonths(months) < tmpFutureDate)
    {
        months++;

        if (months > 12)
        {
            years++;
            months = months - 12;
        }
    }

    if (FutureDate.Day >= myDOB.Day)
    {
        days = days + FutureDate.Day - myDOB.Day;
    }
    else
    {
        months--;

        if (months < 0)
        {
            years--;
            months = months + 12;
        }

        days +=
            DateTime.DaysInMonth(
                FutureDate.AddMonths(-1).Year, FutureDate.AddMonths(-1).Month
            ) + FutureDate.Day - myDOB.Day;

    }

    //add an extra day if the dob is a leap day
    if (DateTime.IsLeapYear(myDOB.Year) && myDOB.Month == 2 && myDOB.Day == 29)
    {
        //but only if the future date is less than 1st March
        if (FutureDate >= new DateTime(FutureDate.Year, 3, 1))
            days++;
    }

}


Matthew Wats.. 21

这是另一个答案:

public static int AgeInYears(DateTime birthday, DateTime today)
{
    return ((today.Year - birthday.Year) * 372 + (today.Month - birthday.Month) * 31 + (today.Day - birthday.Day)) / 372;
}

这已经过广泛的单元测试.它确实看起来有点"神奇".如果每个月有31天,则数字372是一年中的天数.

它起作用的解释(从这里解除)是:

我们来吧 Yn = DateTime.Now.Year, Yb = birthday.Year, Mn = DateTime.Now.Month, Mb = birthday.Month, Dn = DateTime.Now.Day, Db = birthday.Day

age = Yn - Yb + (31*(Mn - Mb) + (Dn - Db)) / 372

我们知道我们需要的是,Yn-Yb如果已经达到日期,Yn-Yb-1如果没有达到.

a)如果Mn<Mb,我们有-341 <= 31*(Mn-Mb) <= -31 and -30 <= Dn-Db <= 30

-371 <= 31*(Mn - Mb) + (Dn - Db) <= -1

用整数除法

(31*(Mn - Mb) + (Dn - Db)) / 372 = -1

b)如果Mn=MbDn<Db,我们有31*(Mn - Mb) = 0 and -30 <= Dn-Db <= -1

再次使用整数除法

(31*(Mn - Mb) + (Dn - Db)) / 372 = -1

c)如果Mn>Mb,我们有31 <= 31*(Mn-Mb) <= 341 and -30 <= Dn-Db <= 30

1 <= 31*(Mn - Mb) + (Dn - Db) <= 371

用整数除法

(31*(Mn - Mb) + (Dn - Db)) / 372 = 0

d)如果Mn=MbDn>Db,我们有31*(Mn - Mb) = 0 and 1 <= Dn-Db <= 30

再次使用整数除法

(31*(Mn - Mb) + (Dn - Db)) / 372 = 0

e)如果Mn=MbDn=Db,我们有31*(Mn - Mb) + Dn-Db = 0

因此 (31*(Mn - Mb) + (Dn - Db)) / 372 = 0


rockXrock.. 19

我们需要考虑小于1年的人吗?作为中国文化,我们将小婴儿的年龄描述为2个月或4周.

下面是我的实现,它并不像我想象的那么简单,尤其是像2/28那样处理日期.

public static string HowOld(DateTime birthday, DateTime now)
{
    if (now < birthday)
        throw new ArgumentOutOfRangeException("birthday must be less than now.");

    TimeSpan diff = now - birthday;
    int diffDays = (int)diff.TotalDays;

    if (diffDays > 7)//year, month and week
    {
        int age = now.Year - birthday.Year;

        if (birthday > now.AddYears(-age))
            age--;

        if (age > 0)
        {
            return age + (age > 1 ? " years" : " year");
        }
        else
        {// month and week
            DateTime d = birthday;
            int diffMonth = 1;

            while (d.AddMonths(diffMonth) <= now)
            {
                diffMonth++;
            }

            age = diffMonth-1;

            if (age == 1 && d.Day > now.Day)
                age--;

            if (age > 0)
            {
                return age + (age > 1 ? " months" : " month");
            }
            else
            {
                age = diffDays / 7;
                return age + (age > 1 ? " weeks" : " week");
            }
        }
    }
    else if (diffDays > 0)
    {
        int age = diffDays;
        return age + (age > 1 ? " days" : " day");
    }
    else
    {
        int age = diffDays;
        return "just born";
    }
}

此实现已通过测试用例.

[TestMethod]
public void TestAge()
{
    string age = HowOld(new DateTime(2011, 1, 1), new DateTime(2012, 11, 30));
    Assert.AreEqual("1 year", age);

    age = HowOld(new DateTime(2011, 11, 30), new DateTime(2012, 11, 30));
    Assert.AreEqual("1 year", age);

    age = HowOld(new DateTime(2001, 1, 1), new DateTime(2012, 11, 30));
    Assert.AreEqual("11 years", age);

    age = HowOld(new DateTime(2012, 1, 1), new DateTime(2012, 11, 30));
    Assert.AreEqual("10 months", age);

    age = HowOld(new DateTime(2011, 12, 1), new DateTime(2012, 11, 30));
    Assert.AreEqual("11 months", age);

    age = HowOld(new DateTime(2012, 10, 1), new DateTime(2012, 11, 30));
    Assert.AreEqual("1 month", age);

    age = HowOld(new DateTime(2008, 2, 28), new DateTime(2009, 2, 28));
    Assert.AreEqual("1 year", age);

    age = HowOld(new DateTime(2008, 3, 28), new DateTime(2009, 2, 28));
    Assert.AreEqual("11 months", age);

    age = HowOld(new DateTime(2008, 3, 28), new DateTime(2009, 3, 28));
    Assert.AreEqual("1 year", age);

    age = HowOld(new DateTime(2009, 1, 28), new DateTime(2009, 2, 28));
    Assert.AreEqual("1 month", age);

    age = HowOld(new DateTime(2009, 2, 1), new DateTime(2009, 3, 1));
    Assert.AreEqual("1 month", age);

    // NOTE.
    // new DateTime(2008, 1, 31).AddMonths(1) == new DateTime(2009, 2, 28);
    // new DateTime(2008, 1, 28).AddMonths(1) == new DateTime(2009, 2, 28);
    age = HowOld(new DateTime(2009, 1, 31), new DateTime(2009, 2, 28));
    Assert.AreEqual("4 weeks", age);

    age = HowOld(new DateTime(2009, 2, 1), new DateTime(2009, 2, 28));
    Assert.AreEqual("3 weeks", age);

    age = HowOld(new DateTime(2009, 2, 1), new DateTime(2009, 3, 1));
    Assert.AreEqual("1 month", age);

    age = HowOld(new DateTime(2012, 11, 5), new DateTime(2012, 11, 30));
    Assert.AreEqual("3 weeks", age);

    age = HowOld(new DateTime(2012, 11, 1), new DateTime(2012, 11, 30));
    Assert.AreEqual("4 weeks", age);

    age = HowOld(new DateTime(2012, 11, 20), new DateTime(2012, 11, 30));
    Assert.AreEqual("1 week", age);

    age = HowOld(new DateTime(2012, 11, 25), new DateTime(2012, 11, 30));
    Assert.AreEqual("5 days", age);

    age = HowOld(new DateTime(2012, 11, 29), new DateTime(2012, 11, 30));
    Assert.AreEqual("1 day", age);

    age = HowOld(new DateTime(2012, 11, 30), new DateTime(2012, 11, 30));
    Assert.AreEqual("just born", age);

    age = HowOld(new DateTime(2000, 2, 29), new DateTime(2009, 2, 28));
    Assert.AreEqual("8 years", age);

    age = HowOld(new DateTime(2000, 2, 29), new DateTime(2009, 3, 1));
    Assert.AreEqual("9 years", age);

    Exception e = null;

    try
    {
        age = HowOld(new DateTime(2012, 12, 1), new DateTime(2012, 11, 30));
    }
    catch (ArgumentOutOfRangeException ex)
    {
        e = ex;
    }

    Assert.IsTrue(e != null);
}

希望它有用.


用户甲.. 17

保持简单(可能是愚蠢:)).

DateTime birth = new DateTime(1975, 09, 27, 01, 00, 00, 00);
TimeSpan ts = DateTime.Now - birth;
Console.WriteLine("You are approximately " + ts.TotalSeconds.ToString() + " seconds old.");


Nicholas Car.. 17

我发现的最简单的方法就是这个.它适用于美国和西欧的地区.不能和其他地方说话,特别是像中国这样的地方.在初始计算年龄后,最多只能进行4次比较.

public int AgeInYears(DateTime birthDate, DateTime referenceDate)
{
  Debug.Assert(referenceDate >= birthDate, 
               "birth date must be on or prior to the reference date");

  DateTime birth = birthDate.Date;
  DateTime reference = referenceDate.Date;
  int years = (reference.Year - birth.Year);

  //
  // an offset of -1 is applied if the birth date has 
  // not yet occurred in the current year.
  //
  if (reference.Month > birth.Month);
  else if (reference.Month < birth.Month) 
    --years;
  else // in birth month
  {
    if (reference.Day < birth.Day)
      --years;
  }

  return years ;
}

我正在寻找答案,并注意到没有人提到闰日分娩的监管/法律影响.例如,根据维基百科,如果您出生于2月29日的各个司法管辖区,那么您的非闰年生日会有所不同:

  • 在英国和香港:这是一年中的序数日,所以第二天,3月1日是你的生日.
  • 在新西兰:前一天是2月28日,用于驾驶执照,3月1日用于其他目的.
  • 台湾:2月28日.

而且就我所知,在美国,法规对这个问题保持沉默,使其符合普通法以及各种监管机构如何在其规则中定义事物.

为此,改进:

public enum LeapDayRule
{
  OrdinalDay     = 1 ,
  LastDayOfMonth = 2 ,
}

static int ComputeAgeInYears(DateTime birth, DateTime reference, LeapYearBirthdayRule ruleInEffect)
{
  bool isLeapYearBirthday = CultureInfo.CurrentCulture.Calendar.IsLeapDay(birth.Year, birth.Month, birth.Day);
  DateTime cutoff;

  if (isLeapYearBirthday && !DateTime.IsLeapYear(reference.Year))
  {
    switch (ruleInEffect)
    {
      case LeapDayRule.OrdinalDay:
        cutoff = new DateTime(reference.Year, 1, 1)
                             .AddDays(birth.DayOfYear - 1);
        break;

      case LeapDayRule.LastDayOfMonth:
        cutoff = new DateTime(reference.Year, birth.Month, 1)
                             .AddMonths(1)
                             .AddDays(-1);
        break;

      default:
        throw new InvalidOperationException();
    }
  }
  else
  {
    cutoff = new DateTime(reference.Year, birth.Month, birth.Day);
  }

  int age = (reference.Year - birth.Year) + (reference >= cutoff ? 0 : -1);
  return age < 0 ? 0 : age;
}

应该注意,此代码假定:

  • 西方(欧洲)对年龄的估算
  • 日历,如公历,在一个月末插入一个闰日.


Dakotah Hico.. 17

TimeSpan diff = DateTime.Now - birthdayDateTime;
string age = String.Format("{0:%y} years, {0:%M} months, {0:%d}, days old", diff);

我不确定你是多么希望它回到你身边,所以我只是做了一个可读的字符串.


Rajeshwaran .. 16

这是一个解决方案.

DateTime dateOfBirth = new DateTime(2000, 4, 18);
DateTime currentDate = DateTime.Now;

int ageInYears = 0;
int ageInMonths = 0;
int ageInDays = 0;

ageInDays = currentDate.Day - dateOfBirth.Day;
ageInMonths = currentDate.Month - dateOfBirth.Month;
ageInYears = currentDate.Year - dateOfBirth.Year;

if (ageInDays < 0)
{
    ageInDays += DateTime.DaysInMonth(currentDate.Year, currentDate.Month);
    ageInMonths = ageInMonths--;

    if (ageInMonths < 0)
    {
        ageInMonths += 12;
        ageInYears--;
    }
}

if (ageInMonths < 0)
{
    ageInMonths += 12;
    ageInYears--;
}

Console.WriteLine("{0}, {1}, {2}", ageInYears, ageInMonths, ageInDays);


flindeberg.. 16

这不是一个直接的答案,而是从准科学的角度来看更多关于手头问题的哲学推理.

我认为这个问题没有说明衡量年龄的单位或文化,大多数答案似乎都假设一个整数年度表示.时间的SI单位是second,正确的通用答案应该是(当然假设归一化DateTime并且不考虑相对论效应):

var lifeInSeconds = (DateTime.Now.Ticks - then.Ticks)/TickFactor;

以基督徒计算年龄的方式:

var then = ... // Then, in this case the birthday
var now = DateTime.UtcNow;
int age = now.Year - then.Year;
if (now.AddYears(-age) < then) age--;

在财务方面,在计算通常被称为日计数分数的事情时存在类似的问题,该分数大致是给定时期的若干年.年龄问题实际上是衡量问题的时间.

实际/实际(计算所有天"正确")约定的示例:

DateTime start, end = .... // Whatever, assume start is before end

double startYearContribution = 1 - (double) start.DayOfYear / (double) (DateTime.IsLeapYear(start.Year) ? 366 : 365);
double endYearContribution = (double)end.DayOfYear / (double)(DateTime.IsLeapYear(end.Year) ? 366 : 365);
double middleContribution = (double) (end.Year - start.Year - 1);

double DCF = startYearContribution + endYearContribution + middleContribution;

测量时间的另一种常见方式通常是"序列化"(命名此日期约定的人必须认真地进行骚扰):

DateTime start, end = .... // Whatever, assume start is before end
int days = (end - start).Days;

我想知道我们必须走多长时间才能在几秒钟内相对论时代变得比在一生中到目前为止的地球周围太阳周期的粗略近似更有用:)或者换句话说,当一个时期必须给定一个位置或者表示动作本身有效的函数:)


mjb.. 15

与2月28日的任何一年相比,这是能够解决2月29日生日的最准确答案之一.

public int GetAge(DateTime birthDate)
{
    int age = DateTime.Now.Year - birthDate.Year;

    if (birthDate.DayOfYear > DateTime.Now.DayOfYear)
        age--;

    return age;
}


DareDevil.. 14

我有一个自定义的方法来计算年龄,加上奖金验证消息,以防它有帮助:

public void GetAge(DateTime dob, DateTime now, out int years, out int months, out int days)
{
    years = 0;
    months = 0;
    days = 0;

    DateTime tmpdob = new DateTime(dob.Year, dob.Month, 1);
    DateTime tmpnow = new DateTime(now.Year, now.Month, 1);

    while (tmpdob.AddYears(years).AddMonths(months) < tmpnow)
    {
        months++;
        if (months > 12)
        {
            years++;
            months = months - 12;
        }
    }

    if (now.Day >= dob.Day)
        days = days + now.Day - dob.Day;
    else
    {
        months--;
        if (months < 0)
        {
            years--;
            months = months + 12;
        }
        days += DateTime.DaysInMonth(now.AddMonths(-1).Year, now.AddMonths(-1).Month) + now.Day - dob.Day;
    }

    if (DateTime.IsLeapYear(dob.Year) && dob.Month == 2 && dob.Day == 29 && now >= new DateTime(now.Year, 3, 1))
        days++;

}   

private string ValidateDate(DateTime dob) //This method will validate the date
{
    int Years = 0; int Months = 0; int Days = 0;

    GetAge(dob, DateTime.Now, out Years, out Months, out Days);

    if (Years < 18)
        message =  Years + " is too young. Please try again on your 18th birthday.";
    else if (Years >= 65)
        message = Years + " is too old. Date of Birth must not be 65 or older.";
    else
        return null; //Denotes validation passed
}

方法调用此处并传递datetime值(如果服务器设置为USA locale,则为MM/dd/yyyy).将其替换为消息框或要显示的任何容器:

DateTime dob = DateTime.Parse("03/10/1982");  

string message = ValidateDate(dob);

lbldatemessage.Visible = !StringIsNullOrWhitespace(message);
lbldatemessage.Text = message ?? ""; //Ternary if message is null then default to empty string

请记住,您可以按照自己喜欢的方式格式化邮件.


用户甲.. 13

这个解决方案怎么样?

static string CalcAge(DateTime birthDay)
{
    DateTime currentDate = DateTime.Now;         
    int approximateAge = currentDate.Year - birthDay.Year;
    int daysToNextBirthDay = (birthDay.Month * 30 + birthDay.Day) - 
        (currentDate.Month * 30 + currentDate.Day) ;

    if (approximateAge == 0 || approximateAge == 1)
    {                
        int month =  Math.Abs(daysToNextBirthDay / 30);
        int days = Math.Abs(daysToNextBirthDay % 30);

        if (month == 0)
            return "Your age is: " + daysToNextBirthDay + " days";

        return "Your age is: " + month + " months and " + days + " days"; ;
    }

    if (daysToNextBirthDay > 0)
        return "Your age is: " + --approximateAge + " Years";

    return "Your age is: " + approximateAge + " Years"; ;
}


AEMLoviji.. 11

private int GetAge(int _year, int _month, int _day
{
    DateTime yourBirthDate= new DateTime(_year, _month, _day);

    DateTime todaysDateTime = DateTime.Today;
    int noOfYears = todaysDateTime.Year - yourBirthDate.Year;

    if (DateTime.Now.Month < yourBirthDate.Month ||
        (DateTime.Now.Month == yourBirthDate.Month && DateTime.Now.Day < yourBirthDate.Day))
    {
        noOfYears--;
    }

    return  noOfYears;
}


用户甲.. 9

以下方法(从.NETDateDiff的时间段文件中提取)考虑文化信息的日历:

// ----------------------------------------------------------------------
private static int YearDiff( DateTime date1, DateTime date2 )
{
  return YearDiff( date1, date2, DateTimeFormatInfo.CurrentInfo.Calendar );
} // YearDiff

// ----------------------------------------------------------------------
private static int YearDiff( DateTime date1, DateTime date2, Calendar calendar )
{
  if ( date1.Equals( date2 ) )
  {
    return 0;
  }

  int year1 = calendar.GetYear( date1 );
  int month1 = calendar.GetMonth( date1 );
  int year2 = calendar.GetYear( date2 );
  int month2 = calendar.GetMonth( date2 );

  // find the the day to compare
  int compareDay = date2.Day;
  int compareDaysPerMonth = calendar.GetDaysInMonth( year1, month1 );
  if ( compareDay > compareDaysPerMonth )
  {
    compareDay = compareDaysPerMonth;
  }

  // build the compare date
  DateTime compareDate = new DateTime( year1, month2, compareDay,
    date2.Hour, date2.Minute, date2.Second, date2.Millisecond );
  if ( date2 > date1 )
  {
    if ( compareDate < date1 )
    {
      compareDate = compareDate.AddYears( 1 );
    }
  }
  else
  {
    if ( compareDate > date1 )
    {
      compareDate = compareDate.AddYears( -1 );
    }
  }
  return year2 - calendar.GetYear( compareDate );
} // YearDiff

用法:

// ----------------------------------------------------------------------
public void CalculateAgeSamples()
{
  PrintAge( new DateTime( 2000, 02, 29 ), new DateTime( 2009, 02, 28 ) );
  // > Birthdate=29.02.2000, Age at 28.02.2009 is 8 years
  PrintAge( new DateTime( 2000, 02, 29 ), new DateTime( 2012, 02, 28 ) );
  // > Birthdate=29.02.2000, Age at 28.02.2012 is 11 years
} // CalculateAgeSamples

// ----------------------------------------------------------------------
public void PrintAge( DateTime birthDate, DateTime moment )
{
  Console.WriteLine( "Birthdate={0:d}, Age at {1:d} is {2} years", birthDate, moment, YearDiff( birthDate, moment ) );
} // PrintAge


Dylan Hayes.. 8

我使用ScArcher2的解决方案来准确计算一个人的年龄,但我需要进一步计算它们的月份和日期以及年份.

    public static Dictionary<string,int> CurrentAgeInYearsMonthsDays(DateTime? ndtBirthDate, DateTime? ndtReferralDate)
    {
        //----------------------------------------------------------------------
        // Can't determine age if we don't have a dates.
        //----------------------------------------------------------------------
        if (ndtBirthDate == null) return null;
        if (ndtReferralDate == null) return null;

        DateTime dtBirthDate = Convert.ToDateTime(ndtBirthDate);
        DateTime dtReferralDate = Convert.ToDateTime(ndtReferralDate);

        //----------------------------------------------------------------------
        // Create our Variables
        //----------------------------------------------------------------------
        Dictionary<string, int> dYMD = new Dictionary<string,int>();
        int iNowDate, iBirthDate, iYears, iMonths, iDays;
        string sDif = "";

        //----------------------------------------------------------------------
        // Store off current date/time and DOB into local variables
        //---------------------------------------------------------------------- 
        iNowDate = int.Parse(dtReferralDate.ToString("yyyyMMdd"));
        iBirthDate = int.Parse(dtBirthDate.ToString("yyyyMMdd"));

        //----------------------------------------------------------------------
        // Calculate Years
        //----------------------------------------------------------------------
        sDif = (iNowDate - iBirthDate).ToString();
        iYears = int.Parse(sDif.Substring(0, sDif.Length - 4));

        //----------------------------------------------------------------------
        // Store Years in Return Value
        //----------------------------------------------------------------------
        dYMD.Add("Years", iYears);

        //----------------------------------------------------------------------
        // Calculate Months
        //----------------------------------------------------------------------
        if (dtBirthDate.Month > dtReferralDate.Month)
            iMonths = 12 - dtBirthDate.Month + dtReferralDate.Month - 1;
        else
            iMonths = dtBirthDate.Month - dtReferralDate.Month;

        //----------------------------------------------------------------------
        // Store Months in Return Value
        //----------------------------------------------------------------------
        dYMD.Add("Months", iMonths);

        //----------------------------------------------------------------------
        // Calculate Remaining Days
        //----------------------------------------------------------------------
        if (dtBirthDate.Day > dtReferralDate.Day)
            //Logic: Figure out the days in month previous to the current month, or the admitted month.
            //       Subtract the birthday from the total days which will give us how many days the person has lived since their birthdate day the previous month.
            //       then take the referral date and simply add the number of days the person has lived this month.

            //If referral date is january, we need to go back to the following year's December to get the days in that month.
            if (dtReferralDate.Month == 1)
                iDays = DateTime.DaysInMonth(dtReferralDate.Year - 1, 12) - dtBirthDate.Day + dtReferralDate.Day;       
            else
                iDays = DateTime.DaysInMonth(dtReferralDate.Year, dtReferralDate.Month - 1) - dtBirthDate.Day + dtReferralDate.Day;       
        else
            iDays = dtReferralDate.Day - dtBirthDate.Day;             

        //----------------------------------------------------------------------
        // Store Days in Return Value
        //----------------------------------------------------------------------
        dYMD.Add("Days", iDays);

        return dYMD;
}


用户甲.. 8

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  


cdiggins.. 7

我对Mark Soen的回答做了一个小改动:我重写了第三行,以便可以更轻松地解析表达式.

public int AgeInYears(DateTime bday)
{
    DateTime now = DateTime.Today;
    int age = now.Year - bday.Year;            
    if (bday.AddYears(age) > now) 
        age--;
    return age;
}

为了清晰起见,我还把它变成了一个功能.


musefan.. 6

这很简单,似乎对我的需求是准确的.我为闰年的目的做出了一个假设,即无论何时选择庆祝生日,他们在技术上都不会超过一年,直到自去年生日过去整整365天(即2月28日不会使他们成为一年以上)

DateTime now = DateTime.Today;
DateTime birthday = new DateTime(1991, 02, 03);//3rd feb

int age = now.Year - birthday.Year;

if (now.Month < birthday.Month || (now.Month == birthday.Month && now.Day < birthday.Day))//not had bday this year yet
  age--;

return age;

如果您发现任何问题,请告诉我们;)


Matt Johnson.. 6

这个经典问题值得Noda Time解决方案.

static int GetAge(LocalDate dateOfBirth)
{
    Instant now = SystemClock.Instance.Now;

    // The target time zone is important.
    // It should align with the *current physical location* of the person
    // you are talking about.  When the whereabouts of that person are unknown,
    // then you use the time zone of the person who is *asking* for the age.
    // The time zone of birth is irrelevant!

    DateTimeZone zone = DateTimeZoneProviders.Tzdb["America/New_York"];

    LocalDate today = now.InZone(zone).Date;

    Period period = Period.Between(dateOfBirth, today, PeriodUnits.Years);

    return (int) period.Years;
}

用法:

LocalDate dateOfBirth = new LocalDate(1976, 8, 27);
int age = GetAge(dateOfBirth);

您可能还对以下改进感兴趣:

  • 作为一个IClock而不是使用时钟传递SystemClock.Instance将提高可测试性.

  • 目标时区可能会发生变化,因此您也需要一个DateTimeZone参数.

另请参阅我关于此主题的博客文章:处理生日和其他周年纪念日


CathalMF.. 6

这是在一行中回答这个问题的最简单方法.

DateTime Dob = DateTime.Parse("1985-04-24");

int Age = DateTime.MinValue.AddDays(DateTime.Now.Subtract(Dob).TotalHours/24).Year - 1;

这也适用于闰年.


用户甲.. 6

哇,我不得不在这里发表评论..这么简单的答案太多了

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

希望它可以帮助别人,至少会让别人想到.. :)


John_J.. 5

=== 俗语(从几个月到几岁) ===

如果您只是常用,请输入以下代码作为您的信息:

DateTime today = DateTime.Today;
DateTime bday = DateTime.Parse("2016-2-14");
int age = today.Year - bday.Year;
var unit = "";

if (bday > today.AddYears(-age))
{
    age--;
}
if (age == 0)   // Under one year old
{
    age = today.Month - bday.Month;

    age = age <= 0 ? (12 + age) : age;  // The next year before birthday

    age = today.Day - bday.Day >= 0 ? age : --age;  // Before the birthday.day

    unit = "month";
}
else {
    unit = "year";
}

if (age > 1)
{
    unit = unit + "s";
}

测试结果如下:

The birthday: 2016-2-14

2016-2-15 =>  age=0, unit=month;
2016-5-13 =>  age=2, unit=months;
2016-5-14 =>  age=3, unit=months; 
2016-6-13 =>  age=3, unit=months; 
2016-6-15 =>  age=4, unit=months; 
2017-1-13 =>  age=10, unit=months; 
2017-1-14 =>  age=11, unit=months; 
2017-2-13 =>  age=11, unit=months; 
2017-2-14 =>  age=1, unit=year; 
2017-2-15 =>  age=1, unit=year; 
2017-3-13 =>  age=1, unit=year;
2018-1-13 =>  age=1, unit=year; 
2018-1-14 =>  age=1, unit=year; 
2018-2-13 =>  age=1, unit=year; 
2018-2-14 =>  age=2, unit=years; 


用户甲.. 5

    private int GetYearDiff(DateTime start, DateTime end)
    {
        int diff = end.Year - start.Year;
        if (end.DayOfYear < start.DayOfYear) { diff -= 1; }
        return diff;
    }
    [Fact]
    public void GetYearDiff_WhenCalls_ShouldReturnCorrectYearDiff()
    {
        //arrange
        var now = DateTime.Now;
        //act
        //assert
        Assert.Equal(24, GetYearDiff(new DateTime(1992, 7, 9), now)); // passed
        Assert.Equal(24, GetYearDiff(new DateTime(1992, now.Month, now.Day), now)); // passed
        Assert.Equal(23, GetYearDiff(new DateTime(1992, 12, 9), now)); // passed
    }


提问时间:

查看次数:

519379 次

最近活跃:

1 年,1 月 前