给定代表某人生日的DateTime,我如何计算他们的年龄(以年为单位)?
当前回答
只需使用:
(DateTime.Now - myDate).TotalHours / 8766.0
当前日期-myDate=TimeSpan,获取总小时数并除以每年的总小时数,得到确切的年龄/月/日。。。
其他回答
我强烈建议使用名为AgeCalculator的NuGet软件包,因为在计算年龄(闰年、时间成分等)时需要考虑很多事情,而且只有两行代码不能削减它。该库给您的时间不只是一年。它甚至在计算时考虑了时间成分,这样你就可以得到一个包含年、月、日和时间成分的准确年龄。更为先进的是,可以选择将2月29日作为闰年,而将2月28日作为非闰年。
SQL版本:
declare @dd smalldatetime = '1980-04-01'
declare @age int = YEAR(GETDATE())-YEAR(@dd)
if (@dd> DATEADD(YYYY, -@age, GETDATE())) set @age = @age -1
print @age
我的建议
int age = (int) ((DateTime.Now - bday).TotalDays/365.242199);
这一年似乎在正确的日期发生了变化。(我在107岁之前进行了现场测试。)
我只想这样做:
DateTime birthDay = new DateTime(1990, 05, 23);
DateTime age = DateTime.Now - birthDay;
这样你就可以计算出一个人的确切年龄,如果你愿意的话,可以精确到毫秒。
这个解决方案怎么样?
static string CalcAge(DateTime birthDay)
{
DateTime currentDate = DateTime.Now;
int approximateAge = currentDate.Year - birthDay.Year;
int daysToNextBirthDay = (birthDay.Month * 30 + birthDay.Day) -
(currentDate.Month * 30 + currentDate.Day) ;
if (approximateAge == 0 || approximateAge == 1)
{
int month = Math.Abs(daysToNextBirthDay / 30);
int days = Math.Abs(daysToNextBirthDay % 30);
if (month == 0)
return "Your age is: " + daysToNextBirthDay + " days";
return "Your age is: " + month + " months and " + days + " days"; ;
}
if (daysToNextBirthDay > 0)
return "Your age is: " + --approximateAge + " Years";
return "Your age is: " + approximateAge + " Years"; ;
}
推荐文章
- 输入对象的datetime。Datetime没有Datetime属性
- 流。Seek(0, SeekOrigin.Begin)或Position = 0
- 如果查询为空,则最大返回值
- "输出类型为类库的项目不能直接启动"
- 传递一个实例化的系统。类型作为泛型类的类型参数
- 从SqlCommand对象获取生成的SQL语句?
- 把内容放在HttpResponseMessage对象?
- 在c#中转换字符串为类型
- 如何比较单元测试中的列表
- 替换c#字符串中的多个字符
- 将XML字符串转换为对象
- ToList()——它是否创建一个新列表?
- .NET中的闭包是什么?
- 连接网络共享时,如何提供用户名和密码
- ProcessStartInfo挂在“WaitForExit”?为什么?