检查字符串是否包含日期

11

给定一个字符串"15:30:20""2011-09-02 15:30:20",我该如何动态地检查一个给定的字符串是否包含日期?

我该如何在代码中检查给定的字符串是否包含日期?

"15:30:20" -> Not Valid

"2011-09-02 15:30:20" => Valid

可能是重复的 https://dev59.com/jXVD5IYBdhLWcg3wQZQg - Zenwalker
4个回答

22

使用DateTime.TryParseExact 方法。

string []format = new string []{"yyyy-MM-dd HH:mm:ss"};
string value = "2011-09-02 15:30:20";
DateTime datetime;

if (DateTime.TryParseExact(value, format, System.Globalization.CultureInfo.InvariantCulture,System.Globalization.DateTimeStyles.NoCurrentDateDefault  , out datetime))
   Console.WriteLine("Valid  : " + datetime);
else
  Console.WriteLine("Invalid");

13

你可以使用

bool b = DateTime.TryParseExact("15:30:20", "yyyy-MM-dd HH:mm:ss",CultureInfo.InvariantCulture,DateTimeStyles.AssumeLocal,out datetime);

检查一个字符串是否可以解析为 DateTime。


如果使用上述解决方案,我的2个样本将始终显示为true。我想检查字符串是否不包含日期,然后显示false。 - Su Beng Keong
这是假设日期始终以该格式呈现。我想知道这是否是OP想要的。 - RichK
@RichK 说得好,但是OP指出输入是字符串,所以我认为我的假设是正确的。 - Dominik

1
使用此方法检查字符串是否为日期:
    private bool CheckDate(String date)
    {
        try
        {
            DateTime dt = DateTime.Parse(date);
            return true;
        }
        catch
        {
            return false;
        }
    }

1
对于.NET Core 2.0,
DateTime.TryParseExact("2017-09-02", "dd MMM yyyy", CultureInfo.InvariantCulture, DateTimeStyles.NoCurrentDateDefault, out DateTime dtDateTime)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接