给定代表某人生日的DateTime,我如何计算他们的年龄(以年为单位)?
当前回答
我经常用手指数。我需要看一下日历,以确定事情何时发生变化。这就是我在代码中要做的:
int AgeNow(DateTime birthday)
{
return AgeAt(DateTime.Now, birthday);
}
int AgeAt(DateTime now, DateTime birthday)
{
return AgeAt(now, birthday, CultureInfo.CurrentCulture.Calendar);
}
int AgeAt(DateTime now, DateTime birthday, Calendar calendar)
{
// My age has increased on the morning of my
// birthday even though I was born in the evening.
now = now.Date;
birthday = birthday.Date;
var age = 0;
if (now <= birthday) return age; // I am zero now if I am to be born tomorrow.
while (calendar.AddYears(birthday, age + 1) <= now)
{
age++;
}
return age;
}
在LINQPad中运行此过程可获得以下结果:
PASSED: someone born on 28 February 1964 is age 4 on 28 February 1968
PASSED: someone born on 29 February 1964 is age 3 on 28 February 1968
PASSED: someone born on 31 December 2016 is age 0 on 01 January 2017
LINQPad中的代码在这里。
其他回答
这里有一个单行线:
int age = new DateTime(DateTime.Now.Subtract(birthday).Ticks).Year-1;
哇,我不得不在这里回答。。。这么简单的问题有很多答案。
private int CalcularIdade(DateTime dtNascimento)
{
var nHoje = Convert.ToInt32(DateTime.Today.ToString("yyyyMMdd"));
var nAniversario = Convert.ToInt32(dtNascimento.ToString("yyyyMMdd"));
double diff = (nHoje - nAniversario) / 10000;
var ret = Convert.ToInt32(Math.Truncate(diff));
return ret;
}
无分支解决方案:
public int GetAge(DateOnly birthDate, DateOnly today)
{
return today.Year - birthDate.Year + (((today.Month << 5) + today.Day - ((birthDate.Month << 5) + birthDate.Day)) >> 31);
}
一句话的回答:
DateTime dateOfBirth = Convert.ToDateTime("01/16/1990");
var age = ((DateTime.Now - dateOfBirth).Days) / 365;
为了计算一个人的年龄,
DateTime dateOfBirth;
int ageInYears = DateTime.Now.Year - dateOfBirth.Year;
if (dateOfBirth > today.AddYears(-ageInYears )) ageInYears --;
推荐文章
- HTTP POST返回错误:417“期望失败。”
- 如何在。net中创建和使用资源
- 为什么Path。以Path.DirectorySeparatorChar开头的文件名合并不正确?
- 如何在c#中获得正确的时间戳
- Linq选择列表中存在的对象(A,B,C)
- c# .NET中的App.config是什么?如何使用它?
- c#:如何获得一个字符串的第一个字符?
- String类中的什么方法只返回前N个字符?
- 如何在PowerShell格式化日期时间
- 我如何提高ASP。NET MVC应用程序性能?
- 更好的方法将对象转换为int类型
- 我可以将c#字符串值转换为转义字符串文字吗?
- 在c#中转换char到int
- c#中朋友的对等物是什么?
- 关键字使用virtual+override vs. new