可能重复:
How do I calculate someone’s age in C#?计算两个日期之间的差异并获得年份的值?
我想基本上计算雇员的年龄 - 因此,我们必须DOB每个员工,所以在 的C#方我要像做这 -
int age=Convert.Int32(DateTime.Now-DOB);
我可以使用天和操作,然后得到年龄...但我想知道是否有东西我可以直接使用获得年数。
可能重复:
How do I calculate someone’s age in C#?计算两个日期之间的差异并获得年份的值?
我想基本上计算雇员的年龄 - 因此,我们必须DOB每个员工,所以在 的C#方我要像做这 -
int age=Convert.Int32(DateTime.Now-DOB);
我可以使用天和操作,然后得到年龄...但我想知道是否有东西我可以直接使用获得年数。
您是否想要计算员工年龄?然后你可以使用这个片段(从Calculate age in C#):
DateTime now = DateTime.Today;
int age = now.Year - bday.Year;
if (bday > now.AddYears(-age)) age--;
如果不是,请指定。我很难理解你想要什么。
Math.Round(DateTime.Now.Subtract(DOB).TotalDays/365.0)
正如指出的那样,这是不行的。您必须这样做:
(Int32)Math.Round((span.TotalDays - (span.TotalDays % 365.0))/365.0);
并且在那一点,另一个解决方案不太复杂,并且在较大跨度上仍然准确。
编辑2,怎么样:
Math.Floor(DateTime.Now.Subtract(DOB).TotalDays/365.0)
基督我在数学基础,这些天吸...
在this网站,他们有:
public static int CalculateAge(DateTime BirthDate)
{
int YearsPassed = DateTime.Now.Year - BirthDate.Year;
// Are we before the birth date this year? If so subtract one year from the mix
if (DateTime.Now.Month < BirthDate.Month || (DateTime.Now.Month == BirthDate.Month && DateTime.Now.Day < BirthDate.Day))
{
YearsPassed--;
}
return YearsPassed;
}
减去2 DateTime
给你一回TimeSpan
。不幸的是,它最大的单位是Days。
虽然不准确,你可以估计它,就像这样:
int days = (DateTime.Today - DOB).Days;
//assume 365.25 days per year
decimal years = days/365.25m;
编辑:哎呦,TotalDays是双,天是一个int。
(DateTime.Now - DOB).TotalDays/365
减去和另外一个DateTime结构为DateTime结构会给你拥有的财产TotalDays时间跨度结构...然后就除以365
不是每年都有365天...... – Rob 2015-02-05 16:08:02
private static Int32 CalculateAge(DateTime DOB)
{
DateTime temp = DOB;
Int32 age = 0;
while ((temp = temp.AddYears(1)) < DateTime.Now)
age++;
return age;
}
除以365不处理闰年实际除以365.25也不准确处理闰年。 – 2010-07-01 04:56:25
雅这就是我想做的事情.. .sorry for not strrasing it well .. – Vishal 2010-06-30 20:10:31
太棒了!没问题。 – alexn 2010-06-30 20:14:38
嗨,你为什么在第三行减少年龄? – WTFZane 2017-03-14 02:57:53