Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Year in Nullable DateTime

Tags:

c#

.net

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?)   
like image 947
user1213055 Avatar asked Mar 30 '12 05:03

user1213055


People also ask

Can DateTime be nullable?

DateTime itself is a value type. It cannot be null.

How do you handle null in DateTime?

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.

Can we assign null to DateTime in C#?

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.

How check date is null or not in C#?

Use model. myDate. HasValue. It will return true if date is not null otherwise false.


2 Answers

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;
}
like image 149
Emond Avatar answered Sep 18 '22 17:09

Emond


First check if it has a Value:

if (date.HasValue == true)
{
    //date.Value.Year;
}
like image 42
ionden Avatar answered Sep 18 '22 17:09

ionden