The below code works fine :
DateTime d1 = DateTime.Now;
DateTime d2 = DateTime.Now.AddDays(-1);
int d3 = (int)(d1 - d2).TotalDays;
But what if I define DateTime
as DateTime?
:
DateTime? d1 = DateTime.Now;
DateTime? d2 = DateTime.Now.AddDays(-1);
int d3 = (int)(d1 - d2).TotalDays;
underlined red with error
Cannot implicitly convert 'System.TimeSpan?' to 'System.TimeSpan'
Is it possible to get the difference of number of days between two datetimes that are defined as nullable?
Well yes, but you need to use the Value
property to "un-null" it:
int d3 = (int)(d1 - d2).Value.TotalDays;
However, you should consider the possibility that either d1
or d2
is null - which won't happen in your case, but could in other cases. You may want:
int? d3 = (int?) (d1 - d2)?.TotalDays;
That will give a result of null
if either d1
or d2
is null
. This is assuming you're using C# 6, of course - otherwise the ?.
operator isn't available.
(You could use GetValueOrDefault()
in the first case as suggested by user3185569, but that would silently use an empty TimeSpan
if either value is null
, which feels unlikely to be what you want.)
See more on this question at Stackoverflow