2010-06-30 81 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

相關問題