Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TimeSpan using a nullable date

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;
}
like image 968
cda01 Avatar asked May 27 '09 09:05

cda01


2 Answers

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;
like image 94
Eric Lippert Avatar answered Nov 11 '22 08:11

Eric Lippert


Try this:

weeksOnPlanSpan = DateTime.Now.Subtract(planStartDate.Value); 
like image 23
Jakob Christensen Avatar answered Nov 11 '22 08:11

Jakob Christensen