TimeSpan using a nullable date

13,667

Solution 1

Try this:

weeksOnPlanSpan = DateTime.Now.Subtract(planStartDate.Value); 

Solution 2

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;
Share:
13,667
cda01
Author by

cda01

Software developer in Sydney, Australia

Updated on June 04, 2022

Comments

  • cda01
    cda01 about 2 years

    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;
    }