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.)
Yes, using GetValueOrDefault()
:
DateTime? d1 = DateTime.Now;
DateTime? d2 = DateTime.Now.AddDays(-1);
int d3 = (int)(d1 - d2).GetValueOrDefault().TotalDays;
d1 - d2
return Nullable TimeSpan which doesn't directly contains a property called TotalDays
. But using GetValueOrDefault()
you can return a TimeSpan
object and get 0 Total Days if the value was NULL
If you do really expect Null
Values, it is better to differentiate between 0 days (What the above approach returns) and and invalid operation (date - null), (null - date) and (null - null). Then you might need to use another approach:
int? d3 = (int) (d1 - d2)?.TotalDays;
Or if you're using a version prior to C# 6 :
int? d3 = d1.HasValue && d2.HasValue ? (int)(d1 - d2).Value.TotalDays : new int?();
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