views:

269

answers:

3

How can i subtract 2 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;
}
+2  A: 

Try this:

weeksOnPlanSpan = DateTime.Now.Subtract(planStartDate.Value);
Jakob Christensen
A: 

Cast the nullable datetime as a normal datetime.

If you know it is not null, then the cast will work fine.

ck
+3  A: 

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;
Eric Lippert