2010-06-30 80 views

回答

60

您是否想要计算员工年龄?然后你可以使用这个片段(从Calculate age in C#):

DateTime now = DateTime.Today; 
int age = now.Year - bday.Year; 
if (bday > now.AddYears(-age)) age--; 

如果不是,请指定。我很难理解你想要什么。

+0

雅这就是我想做的事情.. .sorry for not strrasing it well .. – Vishal 2010-06-30 20:10:31

+0

太棒了!没问题。 – alexn 2010-06-30 20:14:38

+0

嗨,你为什么在第三行减少年龄? – WTFZane 2017-03-14 02:57:53

0

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) 

基督我在数学基础,这些天吸...

+1

不起作用 - 亚历山大有它 – 2010-06-30 20:09:52

+0

这只会适用于较短的跨度,显然,但如果没有人会超过150岁... – Kendrick 2010-06-30 20:10:41

+0

是的,它不起作用。Timespan需要一个“TotalYears”属性:-) – Kendrick 2010-06-30 20:16:33

5

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; 
    } 
14

减去2 DateTime给你一回TimeSpan。不幸的是,它最大的单位是Days。

虽然不准确,你可以估计它,就像这样:

int days = (DateTime.Today - DOB).Days; 

//assume 365.25 days per year 
decimal years = days/365.25m; 

编辑:哎呦,TotalDays是双,天是一个int。

+0

好的答案!我想知道365.25的分区。为什么不只是365.0。我在其他主题中也发现了,并想知道你是否能够启发我。 – ppolyzos 2010-06-30 20:17:07

+4

.25是由于闰年 – 2010-06-30 20:18:19

+0

我也修复它使用Days而不是TotalDays。 TotalDays是一个双重的,而不是一个整数。既然我们不在乎部分日子...... – Powerlord 2010-06-30 20:25:31

-3
(DateTime.Now - DOB).TotalDays/365 

减去和另外一个DateTime结构为DateTime结构会给你拥有的财产TotalDays时间跨度结构...然后就除以365

+1

不是每年都有365天...... – Rob 2015-02-05 16:08:02

4
private static Int32 CalculateAge(DateTime DOB) 
    { 
     DateTime temp = DOB; 
     Int32 age = 0; 
     while ((temp = temp.AddYears(1)) < DateTime.Now) 
      age++; 
     return age; 
    } 
+0

除以365不处理闰年实际除以365.25也不准确处理闰年。 – 2010-07-01 04:56:25

相关问题