Search code examples
c#asp.netsql-serverdatetimedatetime-conversion

Find TotalDays between two Datetime? variables


   DateTime? arrival = (DateTime?)(t.ArrivalDate.Value);
   DateTime? departure = (DateTime?)(t.DepartureDate);

Okay i know both of them are nullable and .TotalDays does not work on nullable object. So kindly tell me how am i supposed to find days difference between these two objects.

Note: Both objects contains Date(s) i.e. are not null


Solution

  • Since there's no meaningful value to their difference if any of them is null, you only need to concern yourself with the case where they're not:

    DateTime? arrival = (DateTime?)(t.ArrivalDate.Value);
    DateTime? departure = (DateTime?)(t.DepartureDate);
    double? totalDays = arrival.HasValue && departure.HasValue 
       ? (double?)(departure - arrival).GetValueOrDefault().TotalDays
       : null;
    

    The subtraction should work because of implicit casting to DateTime.