venkat
venkat

Reputation: 5738

String based DateTime format or pattern check

I have a datetime string.

string strDate = "20140424_18255375";

How to verify the datetime is having in this format YYYYMMDD_HHmmssff

I tried:

bool isTrue = DateTime.TryParseExact(strDate, "YYYYMMDD_HHmmssff", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);

Please help if there is a better way to verify the datetimes with RegEx or any normal way.

Upvotes: 0

Views: 117

Answers (2)

z48o0
z48o0

Reputation: 96

Try this

public override bool IsValid(object value)
{
    var dateString = value as string;
    if (string.IsNullOrWhiteSpace(dateString))
    {
        return true; // Not our problem
    }
    DateTime result;
    var success = DateTime.TryParse(dateString, out result);
    return success;
}

just add your format for date.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1504122

Using TryParseExact is the right way to go about it, but you need to use the right format specifiers. In this case, I think you want:

bool valid =  DateTime.TryParseExact(strDate, "yyyyMMdd_HHmmssff", 
                   CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);

Note the use of yyyy instead of YYYY and dd instead of DD. Format specifiers are case-sensitive.

Upvotes: 6

Related Questions