Подтвердить что ты не робот

Год в Nullable DateTime

Как я могу рассчитать год в дате 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?)   
4b9b3361

Ответ 1

Замените DateofDiagnosis.Year на DateofDiagnosis.Value.Year

И проверьте DateofDiagnosis.HasValue, чтобы убедиться, что он не первый.

Ответ 2

Сначала проверьте, имеет ли он Value:

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

Ответ 3

Используйте значение nullableDateTime.Value.Year.

Ответ 4

Ваш код может выглядеть так,

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