2012-03-30 19 views
11

Come è possibile calcolare l'anno in una data nullable?Anno in 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--; 
    } 
} 

L'errore è:

'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

funziona con il Real DateTime? Se è così non puoi usare il valore non nullo. Sembra che se è nullo il calcolo dell'anno non è necessario comunque? – TGH

+0

Avresti dovuto cercare su google https://www.google.co.in/search?q=nullable+datetime+in+c%23 – Prakash

risposta

34

Sostituire DateofDiagnosis.Year con DateofDiagnosis.Value.Year

e controllare il DateofDiagnosis.HasValue per essere sicuri che non è un nulla prima.

0

Usa nullableDateTime.Value.Year.

6

In primo luogo verificare se ha un Value:

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

Il codice potrebbe assomigliare a questo,

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