Su Beng Keong
Su Beng Keong

Reputation: 1034

Check if a string contains date or not

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" -> Not Valid

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

Upvotes: 11

Views: 46152

Answers (4)

vml19
vml19

Reputation: 3864

For dotnet core 2.0,

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

Upvotes: 1

Syed Faizan Ali
Syed Faizan Ali

Reputation: 9

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

Upvotes: 1

KV Prajapati
KV Prajapati

Reputation: 94645

Use DateTime.TryParseExact Method.

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

Upvotes: 22

Dominik
Dominik

Reputation: 3362

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.

Upvotes: 13

Related Questions