给定代表某人生日的DateTime,我如何计算他们的年龄(以年为单位)?
当前回答
我想添加希伯来文日历计算(或其他系统。全球化日历可以以相同的方式使用),使用此线程中的重写函数:
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
其他回答
为什么不能简化为检查出生日期?
第一行(var year=end.year-start.year-1;):假设出生日期尚未发生在结束年份。然后检查月份和日期,看看是否发生了;再增加一年。
对闰年情景没有特殊处理。如果不是闰年,你不能创建一个日期(2月29日)作为结束日期,所以如果结束日期是3月1日,而不是28日,生日庆祝活动将被计算在内。下面的函数将将此场景作为普通日期进行描述。
static int Get_Age(DateTime start, DateTime end)
{
var year = end.Year - start.Year - 1;
if (end.Month < start.Month)
return year;
else if (end.Month == start.Month)
{
if (end.Day >= start.Day)
return ++year;
return year;
}
else
return ++year;
}
static void Test_Get_Age()
{
var start = new DateTime(2008, 4, 10); // b-date, leap year BTY
var end = new DateTime(2023, 2, 1); // end date is before the b-date
var result1 = Get_Age(start, end);
var success1 = result1 == 14; // true
end = new DateTime(2023, 4, 10); // end date is on the b-date
var result2 = Get_Age(start, end);
var success2 = result2 == 15; // true
end = new DateTime(2023, 6, 22); // end date is after the b-date
var result3 = Get_Age(start, end);
var success3 = result3 == 15; // true
start = new DateTime(2008, 2, 29); // b-date is on feb 29
end = new DateTime(2023, 2, 28); // end date is before the b-date
var result4 = Get_Age(start, end);
var success4 = result4 == 14; // true
end = new DateTime(2020, 2, 29); // end date is on the b-date, on another leap year
var result5 = Get_Age(start, end);
var success5 = result5 == 12; // true
}
我花了一些时间研究这个问题,并用这个来计算某人的年龄,以年、月和日为单位。我已经针对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++;
}
}
要使用最近的年龄计算年龄:
var ts = DateTime.Now - new DateTime(1988, 3, 19);
var age = Math.Round(ts.Days / 365.0);
只是因为我认为最重要的答案不是那么明确:
public static int GetAgeByLoop(DateTime birthday)
{
var age = -1;
for (var date = birthday; date < DateTime.Today; date = date.AddYears(1))
{
age++;
}
return age;
}
对此的简单答案是应用AddYears,如下所示,因为这是唯一一种将年份添加到闰年2月29日的本地方法,并获得普通年份2月28日的正确结果。
有些人认为3月1日是勒普林斯的生日,但.Net和任何官方规则都不支持这一点,也没有常见的逻辑解释为什么一些出生在2月的人应该在另一个月拥有75%的生日。
此外,Age方法可以作为DateTime的扩展添加。由此,您可以以最简单的方式获得年龄:
列表项目
int age=出生日期.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年2月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
}
推荐文章
- 输入对象的datetime。Datetime没有Datetime属性
- 流。Seek(0, SeekOrigin.Begin)或Position = 0
- 如果查询为空,则最大返回值
- "输出类型为类库的项目不能直接启动"
- 传递一个实例化的系统。类型作为泛型类的类型参数
- 从SqlCommand对象获取生成的SQL语句?
- 把内容放在HttpResponseMessage对象?
- 在c#中转换字符串为类型
- 如何比较单元测试中的列表
- 替换c#字符串中的多个字符
- 将XML字符串转换为对象
- ToList()——它是否创建一个新列表?
- .NET中的闭包是什么?
- 连接网络共享时,如何提供用户名和密码
- ProcessStartInfo挂在“WaitForExit”?为什么?