Search code examples
c#stringdatetimetypeconvertertryparse

Test convert string to date time other than DateTime.TryParseExact


Good day,

Normally, If I want to test whether a string is a valid date time format, I will use :

if (DateTime.TryParseExact()){
//do something
}

I would like to ask, is there any code can direct test Convert.ToDateTime() is successful or not? For example like :

if (Convert.ToDateTime(date1)){
//do something
}

or

if(Convert.ToDateTime(date1) == true){
//do soemthing
}

My idea is make it become bool to test it successful convert to date time or not. Just trying to find out the code instead of using DateTime.TryParseExact()


Solution

  • Your first code

    if (DateTime.TryParseExact()) {
        //do something
    }
    

    does exactly what you want.

    Use it like this:

    if (DateTime.TryParseExact(str, ...)) {    // OR use DateTime.TryParse()
        // str is a valid DateTime
    }
    else {
        // str is not valid
    }
    

    You may use DateTime.TryParse() if you don't want to provide a format.
    Both methods returns a boolean value.