2012-03-30 60 views
11

如何计算nullable日期的年份?年Nullable DateTime

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

的错误是:

'System.Nullable<System.DateTime>' does not contain a definition for 'Year' and no 
extension method 'Year' accepting a first argument of 
type 'System.Nullable<System.DateTime>' could be found (are you missing a using 
directive or an assembly reference?) 
+0

是否与真正的日期时间工作吗?如果是这样,你不能使用非空值。看起来好像它是空的,不需要年份计算? – TGH 2012-03-30 05:53:17

+0

您应该搜索了google https://www.google.co.in/search?q=nullable+datetime+in+c%23 – Prakash 2012-03-30 06:44:14

回答

34

更换DateofDiagnosis.YearDateofDiagnosis.Value.Year

并检查DateofDiagnosis.HasValue,以确保它不是空第一。

0

使用nullableDateTime.Value.Year。

6

,如果它有首先检查Value

if (date.HasValue == true) 
{ 
    //date.Value.Year; 
} 
0

您的代码可能会是这样,

partial void AgeAtDiagnosis_Compute(ref int result) 
     { 
      if(DateofDiagnosis.HasValue && DateofBirth.HasValue) 
      { 
       // Set result to the desired field value 
       result = DateofDiagnosis.Value.Year - DateofBirth.Value.Year; 
       if (DateofBirth > DateofDiagnosis.Value.AddYears(-result)) 
       { 
        result--; 
       } 
      } 
     } 
相关问题