在年小数精度时代赋予日期时间 [英] Age in years with decimal precision given a datetime

查看:120
本文介绍了在年小数精度时代赋予日期时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能得到生完孩子的一个C#日期时间的日期一个人的年龄。

How can I get the age of someone given the date of birth in a C# datetime.

我希望有一个精确的年龄一样40.69年老

推荐答案

这将计算确切年龄。年龄的小数部分是相对于上次和下一个生日之间的天数计算,所以它会正确处理闰年。

This will calculate the exact age. The fractional part of the age is calculated relative to the number of days between the last and the next birthday, so it will handle leap years correctly.

小数部分是线性的跨越年份(不考虑个不同长度的),这似乎使最有意义,如果你想表达分数的年龄。

The fractional part is linear across the year (and doesn't take into account the different lengths of the months), which seems to make most sense if you want to express a fractional age.

// 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);

这篇关于在年小数精度时代赋予日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆