2012-03-30 15 views
11

nullableの日付で年を計算するにはどうすればよいですか?Nullableでの年月日

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

それは本当の日時で動作しますか?そうでない場合は、null以外の値を使用できません。とにかく年計算が必要ない場合はnullのように見えますか? – TGH

+0

Googleで検索したはずです。https://www.google.co.in/search?q=nullable+datetime+in+c%23 – Prakash

答えて

34

DateofDiagnosis.Value.Year

DateofDiagnosis.Yearを交換し、それは最初のnullでないことを確認するためにDateofDiagnosis.HasValueを確認してください。それはValueを持っている場合

0

使用nullableDateTime.Value.Year。

6

最初のチェックは:

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--; 
       } 
      } 
     } 
関連する問題