1

A similar question was posted here in regards to calculating the difference in days of 2 datetimes, however both of my datetimes are nullable, which prevents me from using "TotalDays" as is suggested in that question.

DateTime? startDate;
DateTime? endDate;

return(d1-d2).TotalDays;  //This won't work

Any idea how to fix this?

Thanks

goalie35
  • 786
  • 3
  • 14
  • 34
  • Make an if statement to see if either value is null, return null if true, take the `.Value` property if false and do the subtraction. – gunr2171 Jun 21 '19 at 15:28
  • 2
    If either of those are `null`, the result of `d1-d2` will be `null`, so this is also a nullable value, like `Nullable`, you need to decide what to do in this case. – Lasse V. Karlsen Jun 21 '19 at 15:29
  • In your sample code, you never initialize (or use) `startDate` or `endDate`, and neither `d1` nor `d2` are defined. – Rufus L Jun 21 '19 at 15:36

2 Answers2

1

You can do this:

if (startDate.HasValue && endDate.HasValue)
{
    return (startDate.Value - endDate.Value).TotalDays;
}
else
{
    // handle one or more dates being null
}
Owen Pauling
  • 11,349
  • 20
  • 53
  • 64
0

If the value it's null that will throw an exeption,

to prevent this just add a "?" like this:

return(d1-d2)?.TotalDays; 

So if the object is null it won't go any further

GabrSimu
  • 17
  • 4
  • Actually, the original code won't even compile, but this is correct. If the OP does not want `null` in return though, he will need to decide what to return instead, something simple as `return (d1-d2)?.TotalDays ?? 0;` might be enough. – Lasse V. Karlsen Jun 21 '19 at 15:30