Question

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()

Était-ce utile?

La 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.

Autres conseils

If you really want to you can use convert to. However using this means you do not get the features that tryparse can give you.

TryParse:

-Simple if/else validation

-Wont crash and burn your app if bad data is put into it

public static bool
{ 
    TryParse(string s, out DateTime result)
}

Then if else validation

ConvertTo:

-If bad data is put in, your app will crash

-Better to include a try catch into this

-See the msdn article on ConvertTo

 private static void ConvertToDateTime(string value)
 {
  DateTime convertedDate;
  try {
     convertedDate = Convert.ToDateTime(value);
     Console.WriteLine("'{0}' converts to {1} {2} time.", 
                       value, convertedDate, 
                       convertedDate.Kind.ToString());
  }
  catch (FormatException) {
     Console.WriteLine("'{0}' is not in the proper format.", value);
  }
}

In my eyes you should always preference to Tryparse.

As per your comments:

I need to declare a format to check, sometimes the date time format maybe different, thats why I am thinking is there any code like what I think.

TryParseExact already takes a format.

This short example does what you want using TryParseExact. TryParseExact won't throw an exception if the format or date is wrong so you don't have to worry about expensive Try/Catch blocks. Instead it will return false.

static void Main()
{
    Console.Write(ValidateDate("ddd dd MMM h:mm tt yyyy", "Wed 10 Jul 9:30 AM 2013"));
    Console.Read();
}

public static bool ValidateDate(string date, string format)
{
   DateTime dateTime;
   if (DateTime.TryParseExact(date, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime))
   {
       Console.WriteLine(dateTime);
       return true;
   }
   else
   {
       Console.WriteLine("Invalid date or format");
       return false;
   }
}

Or shortened:

public static bool ValidateDate(string date, string format)
{
    DateTime dateTime;
    return DateTime.TryParseExact(date, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime);
}

Then use something like this.

bool isDateTimeValid(string date, string format)
{
    try
    {
        DateTime outDate = DateTime.ParseExact(date, format, Thread.CurrentThread.CurrentUICulture);

        return true;
    }
    catch(Exception exc)
    {
        return false;
    }
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top