检查字符串是否包含日期

时间:2022-09-08 01:44:14

Given a string "15:30:20" and "2011-09-02 15:30:20", How can I dynamically check if a given string contains date or not?

给定字符串“15:30:20”和“2011-09-02 15:30:20”,如何动态检查给定字符串是否包含日期?

"15:30:20" -> Not Valid

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

4 个解决方案

#1


20  

Use DateTime.TryParseExact Method.

使用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");

#2


12  

You can use

您可以使用

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

To check if a string is parsable into DateTime.

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

#3


0  

Use this method to check if string is date or not:

使用此方法检查字符串是否为日期:

    private bool CheckDate(String date)
    {
        try
        {
            DateTime dt = DateTime.Parse(date);
            return true;
        }
        catch
        {
            return false;
        }
    }

#4


0  

For dotnet core 2.0,

对于dotnet core 2.0,

DateTime.TryParseExact("2017-09-02", "dd MMM yyyy", CultureInfo.InvariantCulture, DateTimeStyles.NoCurrentDateDefault, out DateTime dtDateTime)

#1


20  

Use DateTime.TryParseExact Method.

使用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");

#2


12  

You can use

您可以使用

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

To check if a string is parsable into DateTime.

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

#3


0  

Use this method to check if string is date or not:

使用此方法检查字符串是否为日期:

    private bool CheckDate(String date)
    {
        try
        {
            DateTime dt = DateTime.Parse(date);
            return true;
        }
        catch
        {
            return false;
        }
    }

#4


0  

For dotnet core 2.0,

对于dotnet core 2.0,

DateTime.TryParseExact("2017-09-02", "dd MMM yyyy", CultureInfo.InvariantCulture, DateTimeStyles.NoCurrentDateDefault, out DateTime dtDateTime)