c# - 将无效日期处理为有效日期?

标签 c# parsing datetime

我有以下方法,就处理真正的无效/有效日期而言,它可以正常工作,但是,如果我遇到空字符串或带有掩码的日期,例如 __/__/____,我想将它们作为有效传递,但 DateTime.TryParse 使它们无效。我如何修改下面的方法来传递我的无效场景?下面的方法是一个示例程序:

public bool ValidateDate(string date, out string message)
{
    bool success = true;
    message = string.Empty;
    DateTime dateTime;

    if(DateTime.TryParse(date,out dateTime))
    {
        success = false;
        message = "Date is Invalid";
    }

    return success;
}

void Main()
{
    //The only date below that should return false is date4.

    string date = "01/01/2020";
    string date2 = "";
    string date3 = "__/__/____";
    string date4 = "44/__/2013";

    string message;

    ValidateDate(date, out message); //Should return true
    ValidateDate(date2, out message); //Should return true
    ValidateDate(date3, out message); //Should return true
    ValidateDate(date4, out message); //Should return false
}

我无法将其更改为 if(!DateTime.TryParse(date3,out dateTime)),因为这将针对我想要验证的日期返回 false。

我也尝试过类似 if(!date3.contains("_") && DateTime.TryParse(date3,out dateTime)) 的操作,但这仍然失败。我应该翻转我的验证顺序吗?问题是我不只是在第一个无效日期返回 false,我正在构建所有无效日期的 StringBuilder 然后返回它,所以我没想到:

if(DateTime.TryParse(date3,out dateTime))
        return true;
    else
        return true;

public bool ValidateDate(string date, out string message)
{
    string[] overrides = {"","__/__/____"};

    bool success = true;
    message = string.Empty;
    DateTime dateTime;

    if(!overrides.Contains(date) && !DateTime.TryParse(date,out dateTime))
    {
        success = false;
        message = "Date is Invalid";
    }


    return success;
}

最佳答案

在运行 DateTime.TryParse 方法之前,您能否只查看一组覆盖?

static string[] overrides = { "", "__/__/____" };
public bool ValidateDate(string date, out string message)
{
    bool success = true;
    message = string.Empty;

    if(overrides.Contains(date)) { return success; }

    DateTime dateTime;

    if(!DateTime.TryParse(date,out dateTime))
    {
        success = false;
        message = "Date is Invalid";
    }


    return success;
}

关于c# - 将无效日期处理为有效日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17203764/

相关文章:

c# - 有没有办法声明一个类似 Linq 的 CustomWhere() 方法并在没有冗余项的情况下调用它?

c# - 将RSA加密Java代码移植到C#

parsing - 使用 DCG 在 EBNF 的 Prolog 中实现 DSL 的困难

delphi - 如何从 TDateTimePicker 读取日期和时间

python-3.x - 转换 pandas 时间戳列表

c# - 以编程方式调用并呈现 Powerpoint 演示文稿

c# - VS2008 View 设计器/ View 代码快捷方式

c++ - 什么是更有效的 switch case 或 std::map

ios - 数据 > JSON - Swift3 - 转换和解析

java - 日期比较困惑