从字符串解析日期时间而不出错

Sum*_*son 2 c# datetime

我是C#的新手,所以它很可能有一个相当简单的解决方案,但我没有找到任何我认为优雅的东西.如果您需要任何其他信息或对我提出的任何问题感到困惑,请告诉我,我会尽快回复您.

目前创建验证规则的方式(当有人提交表单时),如下所示:

new ValidationRuleInstance<DetailsPresenter>(
    new IsValidDateRule<DetailsPresenter>(m => m.StartDate, "StartDate"),
    new ValidationRuleInterpretation(Severity.Failure, "StartDateMustBeValid", "Must enter valid start date (dd/mm/yyyy)")
),
Run Code Online (Sandbox Code Playgroud)

我正在尝试做的是创建一个验证规则来检查我给出的日期是否发生在过去.我厌倦了这个:

new ValidationRuleInstance<DetailsPresenter>(
    new FailIfTrueRule<DetailsPresenter>(m => (DateTime.Parse(m.StartDate).AddDays(1) < DateTime.Now) ,"StartDate"),
    new ValidationRuleInterpretation(Severity.Failure, "StartDateCannotBeInThePast", "Your start date cannot be in the past")
),
Run Code Online (Sandbox Code Playgroud)

这是有效的...大部分时间(PS我加了一天,所以输入当前日期不会产生错误).

问题是如果有人提交了一个无法解析为日期时间对象的String(例如725/2011而不是7/25/2011),整个事情就会爆发.

我尝试过使用TryParse,但是返回一个布尔值而不是Time-Date对象.

我是否必须编写自己的方法来解析String并始终返回DateTime对象?我可以捕获异常并忽略它吗?(已经有一个单独的规则来检查字符串是否有效)

Ada*_*son 5

没有理由你不能在lambda中使用多行代码块.您只需将代码括在括号中并发出显式return语句,而不是仅指定隐式返回其值的单个表达式.

new ValidationRuleInstance<DetailsPresenter>(
    new FailIfTrueRule<DetailsPresenter>(m => 
{
    DateTime value;

    if(DateTime.TryParse(m.StartDate, out value))
    {
        return value.AddDays(1) < DateTime.Now;
    }
    else // parsing failed, return whatever value is appropriate
    {

    }
} ,"StartDate"),
    new ValidationRuleInterpretation(Severity.Failure, "StartDateCannotBeInThePast", "Your start date cannot be in the past")
),
Run Code Online (Sandbox Code Playgroud)