C# 使用可为空日期的 TimeSpan

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/914802/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 03:05:15  来源:igfitidea点击:

TimeSpan using a nullable date

c#datetime.net-2.0nullable

提问by cda01

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

采纳答案by Jakob Christensen

Try this:

尝试这个:

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

回答by cjk

Cast the nullable datetime as a normal datetime.

将可为空的日期时间转换为正常的日期时间。

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

如果您知道它不为空,则演员表将正常工作。

回答by Eric Lippert

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;