给定代表某人生日的DateTime,我如何计算他们的年龄(以年为单位)?
当前回答
人们可以这样计算“年龄”(即“西方人”的方式):
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;
}
分数是过去的时间(从上一个生日到下一个生日)与总时间的比率。
无论是向前还是向后,这两种方法都以相同的方式工作。
其他回答
我认为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";
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);
}
我创建了一个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.
}
我已经创建了一个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;
}
};
这个解决方案怎么样?
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"; ;
}