checo
checo

Reputation: 49

How to check datetime format in a string?

i got a string with a datetime value so i want to validate that the value is always with this format "yyyy-MM-ddTHH:mm:ss" how can i do that?

i have this code but it´s always throwing true.

  public Boolean validaFecha(string fecha)
    {
        DateTime dDate;
        Boolean resp = false;

        if (DateTime.TryParse(fecha, out dDate))
        {
            resp = true;
        }

        return resp;

    }

Upvotes: 1

Views: 2923

Answers (2)

Fabien ESCOFFIER
Fabien ESCOFFIER

Reputation: 4911

You can use the DateTime.TryParseExact method and specify the format :

public static Boolean validaFecha(string fecha)    
{
    DateTime dDate;
    return DateTime.TryParseExact(fecha, "yyyy-MM-ddTHH:mm:ss", 
        CultureInfo.InvariantCulture, DateTimeStyles.None, out dDate);
}

Example of use :

bool isValid = validaFecha("2015-01-24T12:15:54"); // Will be true

Upvotes: 2

Avia
Avia

Reputation: 1829

Use :

DateTime.TryParseExact Method (String, String, IFormatProvider)

[MSDN Date Time Try Parse Exact][1]

Upvotes: -1

Related Questions