给定代表某人生日的DateTime,我如何计算他们的年龄(以年为单位)?
当前回答
我的建议
int age = (int) ((DateTime.Now - bday).TotalDays/365.242199);
这一年似乎在正确的日期发生了变化。(我在107岁之前进行了现场测试。)
其他回答
我已经创建了一个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"; ;
}
我想添加希伯来文日历计算(或其他系统。全球化日历可以以相同的方式使用),使用此线程中的重写函数:
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
只是因为我认为最重要的答案不是那么明确:
public static int GetAgeByLoop(DateTime birthday)
{
var age = -1;
for (var date = birthday; date < DateTime.Today; date = date.AddYears(1))
{
age++;
}
return age;
}
我使用这个:
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;
}
}