给定代表某人生日的DateTime,我如何计算他们的年龄(以年为单位)?
当前回答
我使用这个:
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;
}
}
其他回答
我只想这样做:
DateTime birthDay = new DateTime(1990, 05, 23);
DateTime age = DateTime.Now - birthDay;
这样你就可以计算出一个人的确切年龄,如果你愿意的话,可以精确到毫秒。
这可能会起作用:
public override bool IsValid(DateTime value)
{
_dateOfBirth = value;
var yearsOld = (double) (DateTime.Now.Subtract(_dateOfBirth).TotalDays/365);
if (yearsOld > 18)
return true;
return false;
}
简单易懂的解决方案。
// 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--;
然而,这假设你在寻找西方的时代观念,而不是使用东亚的推算法。
通过较少的转换和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
);
}
我想添加希伯来文日历计算(或其他系统。全球化日历可以以相同的方式使用),使用此线程中的重写函数:
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
推荐文章
- HTTP POST返回错误:417“期望失败。”
- 如何在。net中创建和使用资源
- 为什么Path。以Path.DirectorySeparatorChar开头的文件名合并不正确?
- 如何在c#中获得正确的时间戳
- Linq选择列表中存在的对象(A,B,C)
- c# .NET中的App.config是什么?如何使用它?
- c#:如何获得一个字符串的第一个字符?
- String类中的什么方法只返回前N个字符?
- 如何在PowerShell格式化日期时间
- 我如何提高ASP。NET MVC应用程序性能?
- 更好的方法将对象转换为int类型
- 我可以将c#字符串值转换为转义字符串文字吗?
- 在c#中转换char到int
- c#中朋友的对等物是什么?
- 关键字使用virtual+override vs. new