2099

Given a DateTime representing a person's birthday, how do I calculate their age in years?

4

70 回答 70

2313

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

// Save today's date.
var today = DateTime.Today;

// Calculate the age.
var age = today.Year - birthdate.Year;

// Go back to the year in which the person was born in case of a leap year
if (birthdate.Date > today.AddYears(-age)) age--;

但是,这假设您正在寻找西方的时代观念,而不是使用东亚推算

于 2008-08-04T16:50:06.170 回答
1075

这是一种奇怪的方法,但是如果您将日期格式化为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;
}
于 2008-08-15T03:47:29.100 回答
407

这是一个测试片段:

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

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

    // For leap years we need this
    if (birthDate > now.AddYears(-age)) 
        age--;
    // Don't use:
    // if (birthDate.AddYears(age) > now) 
    //     age--;

    return age;
}
于 2009-10-20T15:07:22.630 回答
122

对此的简单回答是AddYears如下所示应用,因为这是唯一一种将年份添加到闰年的 2 月 29 日并获得普通年份 2 月 28 日的正确结果的本地方法。

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

此外,Age 方法有助于将其作为扩展添加到DateTime. 通过这种方式,您可以以最简单的方式获得年龄:

  1. 项目清单

int 年龄 = 出生日期.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
}
于 2011-02-19T23:56:58.337 回答
95

我的建议

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

这似乎在正确的日期改变了年份。(我现场测试到 107 岁。)

于 2008-10-03T20:19:31.190 回答
89

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

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 年的中国人 :-)

于 2008-08-01T21:46:12.313 回答
60

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 或 TimeSpan,因为它们会在闰年改变天数
  • 为了可读性,我放了更多的行

还有一点需要注意...我会为它创建 2 个静态重载方法,一个用于通用,第二个用于易用性:

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

public static int GetAge(DateTime birthDay) 
{ 
  return GetAge(birthDay, DateTime.Now);
}
于 2011-04-11T14:47:15.390 回答
53

这是一个单行:

int age = new DateTime(DateTime.Now.Subtract(birthday).Ticks).Year-1;
于 2009-05-18T12:36:51.560 回答
53

The best way that I know of because of leap years and everything is:

DateTime birthDate = new DateTime(2000,3,1);
int age = (int)Math.Floor((DateTime.Now - birthDate).TotalDays / 365.25D);
于 2008-08-01T12:07:19.500 回答
45

这是我们在这里使用的版本。它有效,而且相当简单。这和 Jeff 的想法一样,但我认为它更清晰一点,因为它分离了减一的逻辑,所以更容易理解。

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

如果您认为这种事情不清楚,您可以扩展三元运算符以使其更加清晰。

很明显,这是作为DateTime. 这里我们有另一个重载的 Extension 方法,它传入DateTime.Now,只是为了完整性。

于 2008-08-06T10:23:30.550 回答
36

我用这个:

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;
    }
}
于 2010-02-17T13:32:36.983 回答
36

这为这个问题提供了“更多细节”。也许这就是你要找的

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);
于 2013-09-20T19:13:56.967 回答
30

我创建了一个 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;
    }
};
于 2008-08-23T13:58:02.860 回答
30

这是另一个答案:

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

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

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

让我们设置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

于 2013-04-22T08:19:51.190 回答
26

我花了一些时间研究这个并想出这个来计算某人的年龄,以年、月和日为单位。我已经针对 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++;
    }

}
于 2009-05-18T11:24:38.523 回答
21

我发现的最简单的方法就是这个。它适用于美国和西欧地区。不能和其他地方说话,尤其是像中国这样的地方。在年龄的初始计算之后,最多进行 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 ;
}

我正在查看这个问题的答案,并注意到没有人提到闰日出生的监管/法律影响。例如,根据 Wikipedia,如果您在 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;
}

应该注意的是,此代码假定:

  • 西方(欧洲)的年龄推算,以及
  • 一种日历,例如在月末插入一个闰日的公历。
于 2010-10-06T01:49:50.043 回答
21

保持简单(可能很愚蠢:))。

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.");
于 2010-08-18T14:29:10.410 回答
21

我们需要考虑小于 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);
}

希望它有帮助。

于 2012-11-30T12:13:21.373 回答
20

这不是一个直接的答案,而更多的是从准科学的角度对手头的问题进行哲学推理。

我认为这个问题没有指定衡量年龄的单位或文化,大多数答案似乎都假设整数年度表示。时间的 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--;

在金融中,在计算通常被称为Day Count Fraction的东西时存在类似的问题,它大致是给定时期的年数。年龄问题实际上是一个时间测量问题。

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

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;

我想知道我们需要多长时间才能以秒为单位的相对论年龄变得比迄今为止在一个人的一生中地球绕太阳周期的粗略近似更有用:) 或者换句话说,当一个时期必须被赋予一个位置或一个表示运动的函数本身是有效的:)

于 2012-11-23T15:00:31.097 回答
19
TimeSpan diff = DateTime.Now - birthdayDateTime;
string age = String.Format("{0:%y} years, {0:%M} months, {0:%d}, days old", diff);

我不确定您希望它如何返回给您,所以我只是制作了一个可读的字符串。

于 2013-09-19T15:18:53.443 回答
17

这是一个解决方案。

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);
于 2009-06-18T10:35:21.493 回答
16

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




于 2014-10-23T13:18:40.373 回答
15

我有一个定制的方法来计算年龄,加上一个额外的验证信息,以防万一它有帮助:

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
}

在此处调用方法并传递日期时间值(如果服务器设置为美国语言环境,则为 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

请记住,您可以以任何您喜欢的方式格式化消息。

于 2014-01-22T07:23:00.600 回答
14

这个解决方案怎么样?

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"; ;
}
于 2011-03-08T07:25:02.047 回答
13
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;
}
于 2010-09-06T14:09:01.200 回答
10

以下方法(从.NET类DateDiff的时间段库中提取)考虑了文化信息的日历:

// ----------------------------------------------------------------------
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
于 2011-05-13T08:12:55.700 回答
10

这个经典问题值得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参数。

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

于 2013-12-21T04:53:09.307 回答
10

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  
于 2016-06-30T11:24:56.357 回答
9

我使用 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;
}
于 2011-08-12T20:53:56.410 回答
8

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

为了清楚起见,我还把它变成了一个函数。

于 2011-07-16T18:01:50.027 回答
8

这很简单,似乎对我的需要很准确。我出于闰年的目的做一个假设,无论这个人什么时候选择庆祝生日,他们在技术上不会老一岁,直到他们上一个生日过去了 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;
于 2012-02-24T12:58:54.110 回答
7
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
}
于 2016-10-22T19:10:42.360 回答
7

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

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;
    }
于 2016-09-29T20:13:16.907 回答
7

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

如果您只是为了常用,这里是代码作为您的信息:

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; 
于 2016-05-04T08:29:20.850 回答
5

这可能有效:

public override bool IsValid(DateTime value)
{
    _dateOfBirth =  value;
    var yearsOld = (double) (DateTime.Now.Subtract(_dateOfBirth).TotalDays/365);
    if (yearsOld > 18)
        return true;
    return false;
}
于 2009-11-28T01:58:57.403 回答
5

可以这么简单:

int age = DateTime.Now.AddTicks(0 - dob.Ticks).Year - 1;
于 2015-06-26T16:00:29.003 回答
5

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

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

这也适用于闰年。

于 2016-04-27T14:58:06.170 回答
4

这是我敲出的 C# 的一个小代码示例,请注意边缘情况,特别是闰年,并非所有上述解决方案都将它们考虑在内。将答案作为 DateTime 推出可能会导致问题,因为您最终可能会尝试将太多天放入特定月份,例如 2 月的 30 天。

public string 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 = 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++;
    }

    return "Years: " + years + " Months: " + months + " Days: " + days;
}
于 2009-12-18T14:55:36.833 回答
4

这是一个将年龄计算添加到 DateTime 对象的 DateTime 扩展器。

public static class AgeExtender
{
    public static int GetAge(this DateTime dt)
    {
        int d = int.Parse(dt.ToString("yyyyMMdd"));
        int t = int.Parse(DateTime.Today.ToString("yyyyMMdd"));
        return (t-d)/10000;
    }
}
于 2011-05-20T16:48:34.793 回答
4
public string GetAge(this DateTime birthdate, string ageStrinFormat = null)
{
    var date = DateTime.Now.AddMonths(-birthdate.Month).AddDays(-birthdate.Day);
    return string.Format(ageStrinFormat ?? "{0}/{1}/{2}",
        (date.Year - birthdate.Year), date.Month, date.Day);
}
于 2015-10-12T13:12:02.937 回答
3

我认为 TimeSpan 包含我们需要的所有内容,而不必求助于 365.25(或任何其他近似值)。扩展 Aug 的示例:

DateTime myBD = new DateTime(1980, 10, 10);
TimeSpan difference = DateTime.Now.Subtract(myBD);

textBox1.Text = difference.Years + " years " + difference.Months + " Months " + difference.Days + " days";
于 2008-09-26T20:07:37.550 回答
3

我想添加希伯来日历计算(或其他 System.Globalization 日历可以以相同的方式使用),使用此线程中的重写函数:

Public Shared Function CalculateAge(BirthDate As DateTime) As Integer
    Dim HebCal As New System.Globalization.HebrewCalendar ()
    Dim now = DateTime.Now()
    Dim iAge = HebCal.GetYear(now) - HebCal.GetYear(BirthDate)
    Dim iNowMonth = HebCal.GetMonth(now), iBirthMonth = HebCal.GetMonth(BirthDate)
    If iNowMonth < iBirthMonth Or (iNowMonth = iBirthMonth AndAlso HebCal.GetDayOfMonth(now) < HebCal.GetDayOfMonth(BirthDate)) Then iAge -= 1
    Return iAge
End Function
于 2012-01-11T08:58:06.833 回答
3

我在这个问题上使用了以下内容。我知道这不是很优雅,但它正在工作。

DateTime zeroTime = new DateTime(1, 1, 1);
var date1 = new DateTime(1983, 03, 04);
var date2 = DateTime.Now;
var dif = date2 - date1;
int years = (zeroTime + dif).Year - 1;
Log.DebugFormat("Years -->{0}", years);
于 2015-10-05T17:09:38.217 回答
3

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

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

于 2017-07-16T10:39:21.870 回答
3

只需使用:

(DateTime.Now - myDate).TotalHours / 8766.0

当前日期 - myDate = TimeSpan,获取总小时数并除以每年的总小时数,并获得准确的年龄/月/日...

于 2017-12-15T17:27:13.080 回答
2

我创建了一个 Age 结构,如下所示:

public struct Age : IEquatable<Age>, IComparable<Age>
{
    private readonly int _years;
    private readonly int _months;
    private readonly int _days;

    public int Years  { get { return _years; } }
    public int Months { get { return _months; } }
    public int Days { get { return _days; } }

    public Age( int years, int months, int days ) : this()
    {
        _years = years;
        _months = months;
        _days = days;
    }

    public static Age CalculateAge( DateTime dateOfBirth, DateTime date )
    {
        // Here is some logic that ressembles Mike's solution, although it
        // also takes into account months & days.
        // Ommitted for brevity.
        return new Age (years, months, days);
    }

    // Ommited Equality, Comparable, GetHashCode, functionality for brevity.
}
于 2009-12-16T09:55:00.157 回答
2

试试这个解决方案,它的工作。

int age = (Int32.Parse(DateTime.Today.ToString("yyyyMMdd")) - 
           Int32.Parse(birthday.ToString("yyyyMMdd rawrrr"))) / 10000;
于 2012-07-04T11:28:23.810 回答
2

为什么 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?
于 2013-09-19T13:15:37.123 回答
2

只是因为我认为最佳答案不是那么清楚:

public static int GetAgeByLoop(DateTime birthday)
{
    var age = -1;

    for (var date = birthday; date < DateTime.Today; date = date.AddYears(1))
    {
        age++;
    }

    return age;
}
于 2015-02-17T17:24:51.690 回答
2

通过更少的转换和 UtcNow,这段代码可以照顾在闰年 2 月 29 日出生的人:

public int GetAge(DateTime DateOfBirth)
{
    var Now = DateTime.UtcNow;
    return Now.Year - DateOfBirth.Year -
        (
            (
                Now.Month > DateOfBirth.Month ||
                (Now.Month == DateOfBirth.Month && Now.Day >= DateOfBirth.Day)
            ) ? 0 : 1
        );
}
于 2013-09-08T11:01:48.493 回答
2

这是一个非常简单易学的例子。

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;
}
于 2013-01-02T16:09:02.437 回答
2

这是一个对我很有帮助的功能。不用计算,很简单。

    public static string ToAge(this DateTime dob, DateTime? toDate = null)
    {
        if (!toDate.HasValue)
            toDate = DateTime.Now;
        var now = toDate.Value;

        if (now.CompareTo(dob) < 0)
            return "Future date";

        int years = now.Year - dob.Year;
        int months = now.Month - dob.Month;
        int days = now.Day - dob.Day;

        if (days < 0)
        {
            months--;
            days = DateTime.DaysInMonth(dob.Year, dob.Month) - dob.Day + now.Day;
        }

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


        return string.Format("{0} year(s), {1} month(s), {2} days(s)",
            years,
            months,
            days);
    }

这是一个单元测试:

    [Test]
    public void ToAgeTests()
    {
        var date = new DateTime(2000, 1, 1);
        Assert.AreEqual("0 year(s), 0 month(s), 1 days(s)", new DateTime(1999, 12, 31).ToAge(date));
        Assert.AreEqual("0 year(s), 0 month(s), 0 days(s)", new DateTime(2000, 1, 1).ToAge(date));
        Assert.AreEqual("1 year(s), 0 month(s), 0 days(s)", new DateTime(1999, 1, 1).ToAge(date));
        Assert.AreEqual("0 year(s), 11 month(s), 0 days(s)", new DateTime(1999, 2, 1).ToAge(date));
        Assert.AreEqual("0 year(s), 10 month(s), 25 days(s)", new DateTime(1999, 2, 4).ToAge(date));
        Assert.AreEqual("0 year(s), 10 month(s), 1 days(s)", new DateTime(1999, 2, 28).ToAge(date));

        date = new DateTime(2000, 2, 15);
        Assert.AreEqual("0 year(s), 0 month(s), 28 days(s)", new DateTime(2000, 1, 18).ToAge(date));
    }
于 2015-06-24T11:26:39.537 回答
2

我会这样做:

DateTime birthDay = new DateTime(1990, 05, 23);
DateTime age = DateTime.Now - birthDay;

通过这种方式,您可以计算一个人的确切年龄,如果需要,可以精确到毫秒。

于 2015-07-02T07:37:49.237 回答
2

简单代码

 var birthYear=1993;
 var age = DateTime.Now.AddYears(-birthYear).Year;
于 2017-10-27T06:43:04.703 回答
2
var birthDate = ... // DOB
var resultDate = DateTime.Now - birthDate;

使用resultDate您可以应用TimeSpan任何您想要显示的属性。

于 2018-02-15T11:17:51.823 回答
2

这是计算某人年龄的最简单方法。
计算某人的年龄非常简单,方法如下!为了使代码正常工作,您需要一个名为 BirthDate 的 DateTime 对象,其中包含生日。

 C#
        // get the difference in years
        int years = DateTime.Now.Year - BirthDate.Year; 
        // subtract another year if we're before the
        // birth day in the current year
        if (DateTime.Now.Month < BirthDate.Month || 
            (DateTime.Now.Month == BirthDate.Month && 
            DateTime.Now.Day < BirthDate.Day)) 
            years--;
  VB.NET
        ' get the difference in years
        Dim years As Integer = DateTime.Now.Year - BirthDate.Year
        ' subtract another year if we're before the
        ' birth day in the current year
        If DateTime.Now.Month < BirthDate.Month Or (DateTime.Now.Month = BirthDate.Month And DateTime.Now.Day < BirthDate.Day) Then 
            years = years - 1
        End If
于 2018-02-08T15:10:18.017 回答
1

我强烈建议使用一个名为AgeCalculator的 NuGet 包,因为在计算年龄(闰年、时间分量等)时需要考虑很多事情,而且只有两行代码不能解决问题。图书馆给你的时间不止一年。它甚至在计算时考虑了时间成分,因此您可以获得包含年、月、日和时间成分的准确年龄。更先进的是,可以选择将闰年的 2 月 29 日视为非闰年的 2 月 28 日。

于 2021-09-24T01:24:41.480 回答
0

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

int Age = DateTime.Today.Year - new DateTime(2000, 1, 1).Year;
于 2021-11-15T21:33:05.663 回答
0

我对此一无所知,DateTime但我能做的就是:

using System;
                    
public class Program
{
    public static int getAge(int month, int day, int year) {
        DateTime today = DateTime.Today;
        int currentDay = today.Day;
        int currentYear = today.Year;
        int currentMonth = today.Month;
        int age = 0;
        if (currentMonth < month) {
            age -= 1;
        } else if (currentMonth == month) {
            if (currentDay < day) {
                age -= 1;
            }
        }
        currentYear -= year;
        age += currentYear;
        return age;
    }
    public static void Main()
    {
        int ageInYears = getAge(8, 10, 2007);
        Console.WriteLine(ageInYears);
    }
}

有点混乱,但更仔细地查看代码,这一切都会有意义。

于 2020-10-06T05:44:29.610 回答
0
int Age = new DateTime((DateTime.Now - BirthDate).Ticks).Year -1;
Console.WriteLine("Age {0}", Age);
于 2020-09-27T06:07:33.067 回答
0
var startDate = new DateTime(2015, 04, 05);//your start date
var endDate = DateTime.Now;
var years = 0;
while(startDate < endDate) 
{
     startDate = startDate.AddYears(1);
     if(startDate < endDate) 
     {
         years++;
     }
}
于 2021-08-14T13:35:38.050 回答
0

无分支解决方案:

public int GetAge(DateOnly birthDate, DateOnly today)
{
    return today.Year - birthDate.Year + (((today.Month << 5) + today.Day - ((birthDate.Month << 5) + birthDate.Day)) >> 31);
}
于 2022-01-10T21:43:36.310 回答
0

很简单的答案

        DateTime dob = new DateTime(1991, 3, 4); 
        DateTime now = DateTime.Now; 
        int dobDay = dob.Day, dobMonth = dob.Month; 
        int add = -1; 
        if (dobMonth < now.Month)
        {
            add = 0;
        }
        else if (dobMonth == now.Month)
        {
            if(dobDay <= now.Day)
            {
                add = 0;
            }
            else
            {
                add = -1;
            }
        }
        else
        {
            add = -1;
        } 
        int age = now.Year - dob.Year + add;
于 2020-03-05T08:37:04.467 回答
0

要计算一个人的年龄,

DateTime dateOfBirth;

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

if (dateOfBirth > today.AddYears(-ageInYears )) ageInYears --;
于 2017-10-31T12:09:08.403 回答
0

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

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

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

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

于 2021-09-09T18:22:12.203 回答
0

简单易读的互补方法

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;
}
于 2022-02-19T14:25:44.773 回答
-1

看一下这个:

TimeSpan ts = DateTime.Now.Subtract(Birthdate);
age = (byte)(ts.TotalDays / 365.25);
于 2015-05-09T22:03:15.867 回答
-1

我认为这个问题可以用像这样更简单的方法来解决 -

该课程可以像-

using System;

namespace TSA
{
    class BirthDay
    {
        double ageDay;
        public BirthDay(int day, int month, int year)
        {
            DateTime birthDate = new DateTime(year, month, day);
            ageDay = (birthDate - DateTime.Now).TotalDays; //DateTime.UtcNow
        }

        internal int GetAgeYear()
        {
            return (int)Math.Truncate(ageDay / 365);
        }

        internal int GetAgeMonth()
        {
            return (int)Math.Truncate((ageDay % 365) / 30);
        }
    }
}

电话可以像-

BirthDay b = new BirthDay(1,12,1990);
int year = b.GetAgeYear();
int month = b.GetAgeMonth();
于 2020-09-30T10:10:03.157 回答
-2

计算年龄最近的年龄:

var ts = DateTime.Now - new DateTime(1988, 3, 19);
var age = Math.Round(ts.Days / 365.0);
于 2013-12-03T10:14:42.120 回答
-3

单线答案:

DateTime dateOfBirth = Convert.ToDateTime("01/16/1990");
var age = ((DateTime.Now - dateOfBirth).Days) / 365;
于 2014-07-29T11:46:24.993 回答