Riera
Riera

Reputation: 369

C# Validating date pattern

I'm working in a framework to generate code. One of the properties for date & time fields is its format. It must be a format accepted by DateTime.ToString(), example dd/MM/yyyy. How I can validate if the mask typed in the application is a valid datetime pattern for .ToString()?

Upvotes: 1

Views: 930

Answers (3)

Chris
Chris

Reputation: 27627

Personally if the actual requirement is that a given format must cause DateTime.Now.ToString(format) to not throw an exception then to my mind the most reliable way to do this is to just use that code in a try/catch block and if it throws an exception deal with it as appropriate.

One thing to note is that the ToString code is dependant on a DateTimeFormatInfo object. This may invalidate certain formats though I can't be sure. If it did it would be likely to do with different calendars and such like. It may only be needed for localisation options though. It is certainly worth testing with all (or at least a representative sample) of the locales you are interested in or best case just use the ToString(string format, IFormatProvider provider) overload of DateTime.ToString.

As others have commented on the question programming while expecting exceptions is not usually good practice but in this case I believe this it is the best match because a) it fits the requirements perfectly and b) the other options would be much harder to program and thus be much more likely to have bugs in.

Here's a sample method you might use. Note that I specifically catch the FormatException and not all exceptions in case something else freaky goes wrong that we don't want to catch.

public static bool ValidateDateFormat(string format, IFormatProvider provider)
{
    try
    {
        DateTime.Now.ToString(format, provider);
        return true;
    }
    catch(FormatException)
    {
        return false;
    }
}

Upvotes: 1

Ivan
Ivan

Reputation: 138

First variant uses System.Globalization. Second is dirty.

static bool ValidateFormat(string customFormat)
{
    return !String.IsNullOrWhiteSpace(customFormat) && customFormat.Length > 1 && DateTimeFormatInfo.CurrentInfo.GetAllDateTimePatterns().Contains(customFormat);
}

static bool ValidateFormat(string customFormat)
{
    try
    {
        DateTime.Now.ToString(customFormat);
        return true;
    }
    catch
    {
        return false;
    }
}

Upvotes: 3

shujaat siddiqui
shujaat siddiqui

Reputation: 1587

so simple...

class Program
{
    static void Main(string[] args)
    {
        string s = "yyyy-MM-dd";
        string reg = @"^\bdd/MM/yyyy\b$";
        string reg1 = @"^\byyyy-MM-dd\b$";
        if (Regex.IsMatch(s, reg))
            Console.WriteLine("true");
        else if (Regex.IsMatch(s, reg1))
            Console.WriteLine("true");
        // and so on..

        Console.ReadLine();

    }
}

OR

    static void Main(string[] args)
    {
        string s = "dd/MM/yyyy";
        string reg = @"(?<dateMatch>(^\bdd/MM/yyyy\b$)|(^\byyyy-MM-dd\b$))";

        if (Regex.IsMatch(s, reg))
            Console.WriteLine("true");

        Console.ReadLine();

    }

This method will match the both date patterns. "dd/MM/yyyy" and "yyyy-MM-dd" . Add as many patterns as you want to match.

Upvotes: 0

Related Questions