How can I subtract two dates when one of them is nullable?
public static int NumberOfWeeksOnPlan(User user)
{
DateTime? planStartDate = user.PlanStartDate; // user.PlanStartDate is: DateTime?
TimeSpan weeksOnPlanSpan;
if (planStartDate.HasValue)
weeksOnPlanSpan = DateTime.Now.Subtract(planStartDate); // This line is the problem.
return weeksOnPlanSpan == null ? 0 : weeksOnPlanSpan.Days / 7;
}
To subtract two dates when zero, one or both of them is nullable you just subtract them. The subtraction operator does the right thing; there's no need for you to write all the logic yourself that is already in the subtraction operator.
TimeSpan? timeOnPlan = DateTime.Now - user.PlanStartDate;
return timeOnPlan == null ? 0 : timeOnPlan.Days / 7;
Try this:
weeksOnPlanSpan = DateTime.Now.Subtract(planStartDate.Value);
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