Calculate the difference between two dates and get the value in years?
本问题已经有最佳答案,请猛点这里访问。
Possible Duplicate:
How do I calculate someone’s age in C#?
我想基本上计算雇员的年龄-所以我们每个雇员都有出生日期,以此类推。C面我想做这样的事-
1  | int age=Convert.Int32(DateTime.Now-DOB);  | 
我可以用天来操纵,然后得到年龄……但是我想知道是否有什么东西可以直接用来计算年数。
是否要计算员工的年龄(以年为单位)?然后您可以使用这段代码(从C中计算年龄):
1 2 3  | DateTime now = DateTime.Today; int age = now.Year - bday.Year; if (bday > now.AddYears(-age)) age--;  | 
如果没有,请说明。我很难理解你想要什么。
减去两个
虽然不准确,但您可以这样估计:
1 2 3 4  | int days = (DateTime.Today - DOB).Days; //assume 365.25 days per year decimal years = days / 365.25m;  | 
编辑:哎呀,totaldays是一个双精度数,days是一个整数。
在这个网站上,他们有:
1 2 3 4 5 6 7 8 9 10  |    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; }  | 
1 2 3 4 5 6 7 8  |     private static Int32 CalculateAge(DateTime DOB) { DateTime temp = DOB; Int32 age = 0; while ((temp = temp.AddYears(1)) < DateTime.Now) age++; return age; }  | 
math.round(datetime.now.subtract(dob).totaldays/365.0)
正如所指出的,这行不通。你必须这样做:
1  | (Int32)Math.Round((span.TotalDays - (span.TotalDays % 365.0)) / 365.0);  | 
在这一点上,另一个解决方案就不那么复杂了,而且在更大的跨度上仍然是精确的。
编辑2,如何:
1  | Math.Floor(DateTime.Now.Subtract(DOB).TotalDays/365.0)  | 
天哪,我这几天在基础数学方面很差劲…
1  | (DateTime.Now - DOB).TotalDays/365  | 
从另一个datetime结构中减去datetime结构将为您提供一个具有totaldays属性的TimeSpan结构…然后除以365