Guf*_*ffa 10
这将计算确切的年龄.年龄的小数部分是相对于上一个和下一个生日之间的天数计算的,因此它将正确处理闰年.
小数部分在一年中是线性的(并没有考虑到月份的不同长度),如果你想表达一个分数年龄,这似乎最有意义.
// 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);
Run Code Online (Sandbox Code Playgroud)
这将是一个近似计算:
TimeSpan span = DateTime.Today.Subtract(birthDate);
Console.WriteLine( "Age: " + (span.TotalDays / 365.25).toString() );
Run Code Online (Sandbox Code Playgroud)
顺便说一句:请参阅Stack Overflow上的这个问题:如何计算C#中某人的年龄?
| 归档时间: |
|
| 查看次数: |
8020 次 |
| 最近记录: |