c# - 给定日期时间的年龄(以年为单位,具有小数精度)

标签 c# datetime

如何在 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/

相关文章:

c# - 如何在 IIS 级别的 Asp.Net Core 中配置 MachineKey

ios - swift 中的日期格式问题

javascript - 日期字符串转换浏览器与夏令时的差异

python - 使用 resample 为 pandas 数据框中的不同列聚合具有不同规则的数据

java - 在 Java 中解析日期时间字符串是否需要 `Locale`?

c# - 当异步方法未以 'Async' 结束时,如何在 Visual Studio 中收到警告?

javascript - 使用aurelia上传图像到asp.net core后端

mysql - 将时间和日期转换为mysql日期时间

c# - LINQ to SQL 类,如何更改列格式? (数据网格)

c# - 在我的 C# 应用程序中,Thread.Start 在一些稀疏的情况下没有返回