How can I calculate year in a nullable
date?
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--;
}
}
The error is:
'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?)
DateTime itself is a value type. It cannot be null.
The Nullable < T > structure is using a value type as a nullable type. By default DateTime is not nullable because it is a Value Type, using the nullable operator introduced in C# 2, you can achieve this. Using a question mark (?) after the type or using the generic style Nullable.
CSharp Online Training Using the DateTime nullable type, you can assign the null literal to the DateTime type. A nullable DateTime is specified using the following question mark syntax.
Use model. myDate. HasValue. It will return true if date is not null otherwise false.
Replace DateofDiagnosis.Year
with DateofDiagnosis.Value.Year
And check the DateofDiagnosis.HasValue
to assert that it is not null first.
I would write the code like this:
private bool TryCalculateAgeAtDiagnosis( DateTime? dateOfDiagnosis,
DateTime? dateOfBirth,
out int ageInYears)
{
if (!dateOfDiagnosis.HasValue || !dateOfBirth.HasValue)
{
ageInYears = default;
return false;
}
ageInYears = dateOfDiagnosis.Value.Year - dateOfBirth.Value.Year;
if (dateOfBirth > dateOfDiagnosis.Value.AddYears(-ageInYears))
{
ageInYears--;
}
return true;
}
First check if it has a Value
:
if (date.HasValue == true)
{
//date.Value.Year;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With