开发者

validate the formatString - of Type.ToString(formatString), Is there a builtin provision for this in C#?

开发者 https://www.devze.com 2022-12-08 10:43 出处:网络
for example DateTime dateTime= System.DateTime.Now; //Get the formatString from user , example formatString = \"dddd - d - mmmm\";

for example

DateTime dateTime= System.DateTime.Now;

//Get the formatString from user , example formatString = "dddd - d - mmmm";

//validate the formatStron开发者_开发技巧g provided by the user.

if the format string is valid

string result = dateTime.ToString(formatString);

i know that one way would be to catch the expection while formatting.but i want to know if there is any class/method provided by .Net for this purpose.

Thanks.


Sorry Nar, really misread your initial posting. I am not aware of anything within DateTime to do this but an extension method might help. This extension method encapsulates the try/catch block so you don't have to check it all the time. Now you can check the format with a simple if statement.

    static void Main(string[] args)
    {
        string format = "#";

        DateTime myDate = DateTime.Now;

        if (myDate.ValidateFormat(format))
            Console.WriteLine(myDate.ToString(format));
        else
            Console.WriteLine("Bad format");

        Console.ReadLine();

    }

    static bool ValidateFormat(this object obj, string format)
    {
        try
        {
            MethodInfo info = obj.GetType().GetMethod("ToString", new Type[] { format.GetType() });
            if (info == null)
                return false;
            info.Invoke(obj, new object[] { format });
            return true;
        }
        catch(Exception e)
        {
            Console.WriteLine(e.Message);
            return false;
        }
    }

This ValidateFormat will work for any data type. The only downside is that the extension is on object which means everything will have this method. Those that don't have a ToString(format) meethod report back a false for invalid format.


Update

Turns out there is...DateTime.TryParseExact


If I understand your scenario correctly, you are designing an application where the user can provide a date format for data conversion. You want to ensure that the date format itself is a valid .NET date format string.

If that's the case, what you want to do is test that format string against a known date value using DateTime.TryParseExact, just as others have described:

using System.Globalization; // For CultureInfo & DateTimeStyles    
class MyClass
{
    private bool IsValidDateFormatString(string userSuppliedFormat)
    {
        CultureInfo enUS = new CultureInfo("en-US");
        DateTime testDate = new DateTime(2009, 10, 1, 12, 0, 0); // Noon on Oct 1st 2009
        bool result;

        result = DateTime.TryParseExact(userSuppliedFormat, enUS, DateTimeStyles.None, testDate);

        return result;

    }    
}

This should get you what you want. If necessary, add it as an extension method:

using System.Globalization;
public static class MyClass
{
    private bool IsValidDateFormat(this Date value)
    {
        CultureInfo enUS = new CultureInfo("en-US");
        DateTime testDate = new DateTime(2009, 10, 1, 12, 0, 0); // Noon on Oct 1st 2009
        bool result;

        result = DateTime.TryParseExact(value, enUS, DateTimeStyles.None, testDate);
        return result;        
    }    
}

I'm not sure I'd go that far, however, since it seems like something you'd do very rarely.


I believe the only way to do this is to validate a known-valid date and catch the FormatException. Similar to what Mike Hofer stated, but a call to TryParseExact won't work (see my comments on his answer for why).

try {
    DateTime validDateTime = new DateTime(1904, 01, 31, 12, 59, 59);
    string discarded = validDateTime.ToString(FormatString);

    return true;
}
catch (FormatException) {
    return false;
}
catch (ArgumentOutOfRangeException) {
    return false;   //  But really, the developer is an idiot
}
0

精彩评论

暂无评论...
验证码 换一张
取 消