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

guozao 发布于 2018-02-02 .net 最后更新 2018-02-02 11:24 782 浏览

给定DateTime代表一个人的生日,我怎样计算他们的年龄?

已邀请:

eomnis

赞同来自:

很多年前,为了在我的网站上提供age calculator gimmick,我写了一个函数来计算年龄到一个分数。这是C#的一个快速端口(来自the PHP version)。恐怕我没有能够测试的C#版本,但希望你享受都一样! (不可否认,这对于在Stack Overflow中显示用户配置文件是有点噱头的,但也许读者会发现它的一些用处:-))

double AgeDiff(DateTime date1, DateTime date2) {
    double years = date2.Year - date1.Year;
/*
     * If date2 and date1 + round(date2 - date1) are on different sides
     * of 29 February, then our partial year is considered to have 366
     * days total, otherwise it's 365. Note that 59 is the day number
     * of 29 Feb.
     */
    double fraction = 365
            + (DateTime.IsLeapYear(date2.Year) && date2.DayOfYear >= 59
            && (date1.DayOfYear < 59 || date1.DayOfYear > date2.DayOfYear)
            ? 1 : 0);
/*
     * The only really nontrivial case is if date1 is in a leap year,
     * and date2 is not. So let's handle the others first.
     */
    if (DateTime.IsLeapYear(date2.Year) == DateTime.IsLeapYear(date1.Year))
        return years + (date2.DayOfYear - date1.DayOfYear)/fraction;
/*
     * If date2 is in a leap year, but date1 is not and is March or
     * beyond, shift up by a day.
     */
    if (DateTime.IsLeapYear(date2.Year)) {
        return years + (date2.DayOfYear - date1.DayOfYear
                - (date1.DayOfYear >= 59 ? 1 : 0))/fraction;
    }
/*
     * If date1 is not on 29 February, shift down date1 by a day if
     * March or later. Proceed normally.
     */
    if (date1.DayOfYear != 59) {
        return years + (date2.DayOfYear - date1.DayOfYear
                + (date1.DayOfYear > 59 ? 1 : 0))/fraction;
    }
/*
     * Okay, here date1 is on 29 February, and date2 is not on a leap
     * year. What to do now? On 28 Feb in date2's year, the ``age''
     * should be just shy of a whole number, and on 1 Mar should be
     * just over. Perhaps the easiest way is to a point halfway
     * between those two: 58.5.
     */
    return years + (date2.DayOfYear - 58.5)/fraction;
}

yet

赞同来自:

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

DateTime birthDate = new DateTime(2000,3,1);
int age = (int)Math.Floor((DateTime.Now - birthDate).TotalDays/365.25D);
希望这可以帮助。

mid

赞同来自:

另一个功能,不是由我,而是在网上找到,并提炼一下:

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

hquia

赞同来自:

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

// 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--;
不过,这是假设您正在寻找西方年龄的主意,而不是使用East Asian reckoning

ksit

赞同来自:

这是我们在这里使用的版本。它工作,而且相当简单。这和Jeff的想法是一样的,但是我认为它更清晰一些,因为它将逻辑减去了一个,所以它更容易理解。

public static int GetAge(this DateTime dateOfBirth, DateTime dateAsAt)
{
    return dateAsAt.Year - dateOfBirth.Year - (dateOfBirth.DayOfYear < dateAsAt.DayOfYear ? 0 : 1);
}
如果你认为这样的事情是不清楚的,你可以扩展三元运算符,使之更加清晰。 很明显,这是DateTime上的一个扩展方法,但显然你可以抓住那行代码来完成这个工作,并把它放在任何地方。这里我们有另外一个在DateTime.Now中传递的扩展方法的重载,只是为了完整性。

esaepe

赞同来自:

这是一个奇怪的方法,但如果你将日期的格式设置为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;
}

nrerum

赞同来自:

我不认为迄今为止的答案都提供了计算年龄不同的文化。例如,见East Asian Age Reckoning与西方的相比。 任何现实答案都必须包含本地化。在这个例子中,Strategy Pattern可能是有序的。

mnatus

赞同来自:

我已经创建了一个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;
    }
};

funde

赞同来自:

我认为TimeSpan拥有我们所需要的一切,而不必诉诸于365.25(或任何其他近似)。以八月份的例子展开:

DateTime myBD = new DateTime(1980, 10, 10);
TimeSpan difference = DateTime.Now.Subtract(myBD);
textBox1.Text = difference.Years + " years " + difference.Months + " Months " + difference.Days + " days";

wet

赞同来自:

我的建议

int age = (int) ((DateTime.Now - bday).TotalDays/365.242199);
这似乎有一个正确的日期改变了一年。 (我现场测试到107岁)

funde

赞同来自:

我花了一些时间在这方面做了一些工作,并提出了这个计算年龄,几个月和几天的人的年龄。我已经测试了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++;
    }
}

ueum

赞同来自:

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

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

oautem

赞同来自:

这是一个解决方案。

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

ut_quo

赞同来自:

我不知道如何接受错误的解决方案。 正确的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;
}

wodio

赞同来自:

这会工作吗?

public override bool IsValid(DateTime value)
{
    _dateOfBirth =  value;
    var yearsOld = (double) (DateTime.Now.Subtract(_dateOfBirth).TotalDays/365);
    if (yearsOld > 18)
        return true;
     return false; 
}

iaut

赞同来自:

我创建了一个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.
}

znemo

赞同来自:

这里有一个针对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;
}

bnemo

赞同来自:

我使用这个:

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

bmagni

赞同来自:

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

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.");

emagni

赞同来自:

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

phic

赞同来自:

我找到的最简单的方法是这样的。它适用于美国和西欧的语言环境。不能和其他地区,特别是像中国这样的地方说话。最多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 ;
}
我正在研究这个问题的答案,并注意到没有人提到闰日出生的监管/法律方面的问题。例如,per Wikipedia,如果你是在2月29日出生在不同司法管辖区,那么你是非闰年的生日有所不同:
  • 在英国和香港:这是一年的第二天,所以第二天的三月一日是你的生日。
  • 在新西兰:前一天,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;
    }
    
    应该指出,这个代码假定:
    • 西方(欧洲)年龄的估算,
    • 一个日历,就像公历一样,在一个月的月底插入一个闰日。

yquo

赞同来自:

最简单的答案是应用AddYears,如下所示,因为这是将闰年数加2年到29年的唯一本地方法,并且可以得到2月28日为正常年份的正确结果。 有些人觉得3月1日是跳跳舞的生日,但网络也没有任何官方的规则支持这一点,普通逻辑也没有解释为什么二月份出生的一个月中应该有百分之七十五的生日。 此外,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
}

gvel

赞同来自:

这个解决方案如何?

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

tqui

赞同来自:

2要解决的主要问题是: 1。计算完全age - 年,月,日等 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);
    }
    

siusto

赞同来自:

以下方法(Time Period Library for .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

yquo

赞同来自:

这是一个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;
        }
    }

xid

赞同来自:

我对Mark Soen's做了一个小小的改动:我重写了第三行,以便表达式可以更容易地被解析。

    public int AgeInYears(DateTime bday)
    {
        DateTime now = DateTime.Today;
        int age = now.Year - bday.Year;            
        if (bday.AddYears(age) > now) 
            age--;
        return age;
    }
为了清楚起见,我也把它变成了一个函数。

ueaque

赞同来自:

我使用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;
}

noptio

赞同来自:

我想添加希伯来日历计算(或其他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

zet

赞同来自:

这很简单,似乎对我的需求是准确的。我为了闰年的目的做出了一个假设,无论人们选择什么时候庆祝生日,他们在技术上都不是年龄大一岁,直到自上一个生日之后的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;
让我们知道,如果你发现任何问题;)

nquas

赞同来自:

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

int age = (Int32.Parse(DateTime.Today.ToString("yyyyMMdd")) - 
           Int32.Parse(birthday.ToString("yyyyMMdd rawrrr")))/10000;

oest

赞同来自:

这不是一个直接的答案,而是更多地从一个准科学的观点来看待这个问题的哲学推理。 我认为,这个问题没有具体说明年龄的单位和文化,大多数答案似乎都假定为年度整数。时间的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;
我想知道,在一个相对论的年龄段之前,相对论的年龄在几秒钟之内变得比迄今为止的生命周期中的地球周围太阳周期的粗略近似更有用:)或者换句话说,当一段时间必须给定一个位置或者一个代表运动的函数为自己是有效的:)

get

赞同来自:

我们需要考虑一年以下的人吗?作为中国文化,我们将小婴儿的年龄描述为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);
}
希望这是有帮助的。

but

赞同来自:

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

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

sest

赞同来自:

还有另外一个答案:

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天的一年中的天数。 为什么它的工作原理(lifted from here)是:
Let's set 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 We know that what we need is either Yn-Yb if the date has already been reached, Yn-Yb-1 if it has not. a) If Mn<Mb, we have -341 <= 31*(Mn-Mb) <= -31 and -30 <= Dn-Db <= 30 -371 <= 31*(Mn - Mb) + (Dn - Db) <= -1 With integer division (31*(Mn - Mb) + (Dn - Db))/372 = -1 b) If Mn=Mb and Dn<Db, we have 31*(Mn - Mb) = 0 and -30 <= Dn-Db <= -1 With integer division, again (31*(Mn - Mb) + (Dn - Db))/372 = -1 c) If Mn>Mb, we have 31 <= 31*(Mn-Mb) <= 341 and -30 <= Dn-Db <= 30 1 <= 31*(Mn - Mb) + (Dn - Db) <= 371 With integer division (31*(Mn - Mb) + (Dn - Db))/372 = 0 d) If Mn=Mb and Dn>Db, we have 31*(Mn - Mb) = 0 and 1 <= Dn-Db <= 30 With integer division, again (31*(Mn - Mb) + (Dn - Db))/372 = 0 e) If Mn=Mb and Dn=Db, we have 31*(Mn - Mb) + Dn-Db = 0 and therefore (31*(Mn - Mb) + (Dn - Db))/372 = 0

wiusto

赞同来自:

通过较少的转换和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
        );
}

non_et

赞同来自:

How come the MSDN help did not tell you that? It looks so obvious:
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?

eos_et

赞同来自:

TimeSpan diff = DateTime.Now - birthdayDateTime;
string age = String.Format("{0:%y} years, {0:%M} months, {0:%d}, days old", diff);
我不确定你想如何回复给你,所以我只是做了一个可读的字符串。

pquis

赞同来自:

这给这个问题“更多的细节”。也许这是你在找什么

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

pnon

赞同来自:

计算最近年龄的年龄:

var ts = DateTime.Now - new DateTime(1988, 3, 19);
var age = Math.Round(ts.Days/365.0);

nipsa

赞同来自:

这个经典的问题值得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参数。
  • 另见我的博客文章:Handling Birthdays, and Other Anniversaries

sit_in

赞同来自:

我有一个自定义函数来计算年龄+消息,如果选择日期不匹配     //这个函数会验证日期

private bool ValidateDate(string dob)
{
    DateTime dobdate = DateTime.Parse(dob);
    DateTime nowdate = DateTime.Now;
    TimeSpan ts = nowdate - dobdate;
    int Years = ts.Days/365;
if (Years < 18)
    {
        message = "Date of Birth must not be less then 18";
        return false;
    }
    else if (Years > 65)
    {
        message = "Date of Birth must not be greater then 65";
        return false;
    }
dobvalue = dob;
    return true;
}
//Below here you call that function and pass out datetime value (MM/DD/YYYY) you can format by any way you like
//Function Call
if (ValidateDate("03/10/1982") == false)
{
    lbldatemessaeg.Visible = true;
    lbldatemessaeg.Text = message; //you can replace anything a messagebox,or any container to display
    return;
}

jquia

赞同来自:

int age = DateTime.Now.Year - birthday.Year;
if (DateTime.Now.Month < birthday.Month || DateTime.Now.Month == birthday.Month 
&& DateTime.Now.Day < birthday.Day) age--;

jdolor

赞同来自:

一个线性答案,

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

dodit

赞同来自:

这是能够解决二月二十九日比二月二十八日的任何一年的生日最准确的答案之一。

public int GetAge(DateTime birthDate)
{
    int age = DateTime.Now.Year - birthDate.Year;
if (birthDate.DayOfYear > DateTime.Now.DayOfYear)
        age--;
return age;
}

fet

赞同来自:

只是因为我不认为最重要的答案是明确的:

public static int GetAgeByLoop(DateTime birthday)
{
    var age = -1;
for (var date = birthday; date < DateTime.Today; date = date.AddYears(1))
        age++;
return age;
}

zvelit

赞同来自:

看一下这个:

TimeSpan ts = DateTime.Now.Subtract(Birthdate);
age = (byte)(ts.TotalDays/365.25);

qporro

赞同来自:

这是一个很好的功能...没有calcs,非常简单。

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

dnulla

赞同来自:

为什么不能这么简单?

int age = DateTime.Now.AddTicks(0 - dob.Ticks).Year - 1;

qfugit

赞同来自:

我只是这样做:

DateTime birthDay = new DateTime(1990, 05, 23);
DateTime age = DateTime.Now - birthDay;
这样你就可以计算一个人的确切年龄,如果你愿意,可以计算到毫秒级。

uet

赞同来自:

我不喜欢这里的很多答案,因为他们需要几行代码来做一个非常简单的日期计算(除非你想发表一个覆盖他们的答案,否则请把你所有关于年龄计算的意见保存在其他文化中)。我的一个班轮,使用简单的datemath和数学函数存在于c#,sqlserver,mysql等是:

year(@today)-year(@birthDate)+floor((month(@today)-month(@birthdate)+floor((day(@today)-day(@birthdate))/31))/12)
但是我也非常喜欢Mathew的回答。无论哪种方式比这里给出的其他答案效率更高。

ket

赞同来自:

我用这个问题,我知道,这不是很优雅,但它的工作

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

eomnis

赞同来自:

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

hquia

赞同来自:

这是在一条线上回答这个问题的最简单的方法。

DateTime Dob = DateTime.Parse("1985-04-24");
int Age = DateTime.MinValue.AddDays(DateTime.Now.Subtract(Dob).TotalHours/24).Year - 1;
这也适用于闰年。

dsit

赞同来自:

=== 常见说法(从几个月到几岁) === 如果你只是为了共同使用,这里是代码作为你的信息:

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; 

ea_qui

赞同来自:

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  

tut

赞同来自:

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

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;
    }
希望它可以帮助别人,至少会让别人觉得.. :)

pporro

赞同来自:

    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
    }

xqui

赞同来自:

我经常指望我的手指。当事情发生变化时,我需要查看一个日历来解决问题。所以这就是我的代码:

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中的代码是here

baut

赞同来自:

简单的代码

 var birthYear=1993;
 var age = DateTime.Now.AddYears(-birthYear).Year;

vomnis

赞同来自:

这很简单

var byear=1990;
var age = DateTime.Now.Year - byear;