Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a string contains date or not

Tags:

c#

.net

datetime

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
like image 260
Su Beng Keong Avatar asked Sep 02 '11 07:09

Su Beng Keong


People also ask

How do you check if a string is date or not?

new Date(date) !== "Invalid Date" will always return true since the left expression will return a Date object with a timevalue of NaN, which can never be === to a string. Using == "works" due to type conversion.

How check string is date or not in C#?

TryParse() function to check if a particular string is a valid datetime not depending on any cultures. To my surprise , the function returns true for even strings like "1-1", "1/1" . etc.

How do you validate a date?

The date validator requires day, month and year. If you are looking for hour and time validator, HH:mm , for example, you should use the regexp validator. Below are some example of possible formats: YYYY/DD/MM.


2 Answers

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;
        }
    }
like image 95
Syed Faizan Ali Avatar answered Sep 17 '22 09:09

Syed Faizan Ali


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.

like image 39
Dominik Avatar answered Sep 19 '22 09:09

Dominik