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
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.
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.
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.
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;
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With