C# 从日期时间(出生日期)算起的年龄
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/673476/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Age in years from DateTime (Date of birth)
提问by
Duplicate
复制
I have a datetime
variable that represents the date of birth of a user.
我有一个datetime
代表用户出生日期的变量。
How can I get the age in years from this?
我怎样才能从中得到年龄?
UpdateI want a precise birthday, so 30.45 years or something.
更新我想要一个精确的生日,所以 30.45 年或什么的。
回答by
You can try with (in Vb):
您可以尝试使用(在 Vb 中):
Dim dateOfBirth As Date
Now.Subtract(dateOfBirth).TotalDays \ 365
\ is an Integer division in Vb, I do not know if it has a correspondant in C#.
\是Vb中的整数除法,不知道C#有没有对应。
回答by Mark Pim
Try the following (assuming the date of birth is stored in dtDOB
):
尝试以下操作(假设出生日期存储在 中dtDOB
):
public int getAgeInYears {
TimeSpan tsAge = DateTime.Now.Subtract(dtDOB);
return new DateTime(tsAge.Ticks).Year - 1;
}
回答by Nathan DeWitt
Stolen from the answer to Jeff's question:
从杰夫问题的答案中窃取:
DateTime now = DateTime.Now;
int age = now.Year - bday.Year;
if (now < bday.AddYears(age)) age--;