Check if a string is a valid date

Asked

Viewed 772 times

3

How do I check whether the date is valid in C or not#?

In VB6 I did like this:

If Not IsDate(strAux) Then

In the case of C#, how do I?

My code in C#:

//Data Movimento
string strTxt = fileHeader.Substring(17, 8).ToString("YYYYMMDD");

if (!Equals(strTxt))  // verificar se é data válida  
{
    // logFile "ERRO", "Data de Movimento invalida no Header no arquivo."    
    return null;
}

1 answer

4

I don’t understand what you wanted to do in your code, but from the description of the problem, I imagine you’re looking for the method DateTime.TryParseExact.

Note that the second argument of the method is the format that will be used to validate the string.

DateTime data;
bool dataValida = DateTime.TryParseExact(strTxt, "YYYYMMDD", CultureInfo.InvariantCulture, 
                                         DateTimeStyles.None, out data);

if(!dataValida)
    ...
  • Thank you very much!!! that’s right.

  • @Thathi You can mark the answer as correct using the V on the left side of it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.