2012-02-16 26 views
1

我在數據庫中捕獲出生日期和診斷日期,並且想要根據診斷日期計算年齡。屬性或索引器不能被分配到 - 它是隻讀的

這是我的代碼。但我有錯誤跟隨錯誤。

錯誤2屬性或索引 'LightSwitchApplication.Patient.AgeAtDiagnosis' 不能被分配到 - 只

partial void AgeAtDiagnosis_Compute(ref int result) 
{ 
     // Set result to the desired field value 
     AgeAtDiagnosis = DateofDiagnosis.Year - DateofBirth.Year; 
     if (DateofBirth > DateofDiagnosis.AddYears(-AgeAtDiagnosis)) 
     { 
      AgeAtDiagnosis--; 
     } 
} 
+0

爲什麼'string'結果? – 2012-02-16 10:42:23

+0

不會簡單的減去嗎? – SWeko 2012-02-16 10:42:36

+0

你可以從這裏找到確切的解決方案http://stackoverflow.com/questions/9/how-do-i-calculate-someones-age-in-c – 2012-02-16 10:44:49

回答

2
DateTime birth = new DateTime(1950, 01, 01); 
DateTime diagnosis = new DateTime(2012, 02, 01); 
TimeSpan Span = diagnosis - birth; 
DateTime Age = DateTime.MinValue + Span; 
// note: MinValue is 1/1/1 so we have to subtract... 
int Years = Age.Year - 1; 
+0

來源:http://forums.asp.net/post/ 2486703.aspx – Schiavini 2012-02-16 10:45:45

+0

+1必須是這樣的話。 – 2012-02-16 10:46:43

1
TimeSpane age0 = this.DateOfDiagnosis - this.DateOfBirth; 

int age1 = (int) Math.Trunc(age0.TotalDays/365.25); 
+0

TotalYears在TimeSpan中也不存在。 – Schiavini 2012-02-16 10:44:41

0

您只需減一讀來自另一個的時間給予TimeSpan。這有一個TotalDays屬性,您可以從中獲取多年。這取決於你想如何準確的是:

var ageInDays = (diagnoticDate - dateOfBirth).TotalDays; 
var age = Convert.ToInt32(ageInDays/365); 

顯然閏年導致問題,因此另一種方法是檢查每個日期的年份,月份和日期的屬性,並計算它們的差異分別考慮到部分年等

相關問題