可能重複:
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