如何在 C# 日期时间中根据出生日期获取某人的年龄。
我想要一个精确的年龄,比如 40.69 岁
最佳答案
这将计算出准确的年龄。年龄的小数部分是相对于上一个生日和下一个生日之间的天数计算的,因此它将正确处理闰年。
小数部分在一年中是线性的(并且没有考虑月份的不同长度),如果您想表达小数年龄,这似乎最有意义。
// birth date
DateTime birthDate = new DateTime(1968, 07, 14);
// get current date (don't call DateTime.Today repeatedly, as it changes)
DateTime today = DateTime.Today;
// get the last birthday
int years = today.Year - birthDate.Year;
DateTime last = birthDate.AddYears(years);
if (last > today) {
last = last.AddYears(-1);
years--;
}
// get the next birthday
DateTime next = last.AddYears(1);
// calculate the number of days between them
double yearDays = (next - last).Days;
// calcluate the number of days since last birthday
double days = (today - last).Days;
// calculate exaxt age
double exactAge = (double)years + (days / yearDays);
关于c# - 给定日期时间的年龄(以年为单位,具有小数精度),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/673514/