2012-03-30 15 views
11

Jak mogę obliczyć rok w nullable datę?Rok w 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--; 
    } 
} 

Błąd jest:

'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

Czy to działa z prawdziwym DateTime? Jeśli tak, nie możesz użyć wartości niepustej. Wydaje się, że jeśli jest zerowa, obliczenia roku i tak nie są potrzebne? – TGH

+0

Powinieneś wyszukiwać google https://www.google.co.in/search?q=nullable+datetime+w+c%23 – Prakash

Odpowiedz

34

Wymień DateofDiagnosis.Year z DateofDiagnosis.Value.Year

I sprawdzić DateofDiagnosis.HasValue aby mieć pewność, że nie jest to pierwszy null.

0

Zastosowanie nullableDateTime.Value.Year.

6

Najpierw należy sprawdzić, czy posiada on Value:

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

Twój kod może wyglądać tak,

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