简体   繁体   中英

How to validate date format in C#

I want to check if a given string is a valid .net date format.

so i have the following function that checks if the date format is correct

    public void IsValidDateFormat(string dateFormat)
    {
        var flag = true;
        try
        {
            DateTime.ParseExact(DateTime.Now.ToString(),
                dateFormat,
                System.Globalization.CultureInfo.InvariantCulture);
        }
        catch (Exception ex)
        {
            flag = false;
        }

       return flag;
    }

However, The method is not working as expected. For a valid date format also it returns false.

dateFormat = ,, => returns false =>Passed
dateFormat = someinvalidformat => returns false =>Passed
dateFormat = MM/dd/yyyy => returns false => Not Passed

So MM/dd/yyyy is valid dateformat. But method returns false.

Is there a better way to check if given date format is valid .Net date format?

Update 1
I understand why method fails for MM/dd/yyyy or for other valid date formats. I am not asking why it fails. MM/dd/yyyy is just common valid date time format i am using here for example.
I am looking for a way to check if the given date format is valid .Net date format. So it could be any .Net date format.

Since the format returned by DateTime.ToString does not match your format (it includes the time part), ParseExact fails.

Validate the format by using public string ToString(string format, System.IFormatProvider provider) instead

public bool IsValidDateFormat(string dateFormat)
{
    try {
        string s = DateTime.Now.ToString(dateFormat, CultureInfo.InvariantCulture);
        DateTime.Parse(s, CultureInfo.InvariantCulture);
        return true;
    } catch {
        return false;
    }
}

Note that date/time formats that may seem not to be valid, can in fact be valid, as some non-format characters are just outputted as is. Eg

DateTime.Now.ToString("abcdefg", CultureInfo.InvariantCulture)

results in "abc27e6A.D." . So it is in fact a valid date/time format, even if it does not make a lot of sense. You can enhance the quality of the test by trying to parse the resulting date string. This will eliminate a lot of nonsensical formats.

This test ...

Console.WriteLine(IsValidDateFormat(",,"));
Console.WriteLine(IsValidDateFormat("a"));
Console.WriteLine(IsValidDateFormat("MM/dd/yyyy hh:mm:ss"));
Console.WriteLine(IsValidDateFormat("MM/dd/yyyy"));
Console.WriteLine(IsValidDateFormat("abcdefg"));
Console.ReadKey();

... prints

False
False
True
True
False

why not TryParse() or exact version? https://docs.microsoft.com/es-es/dotnet/api/system.datetime.tryparse?view=netframework-4.8

returns true if system can parse.

It does "the same" your method does.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM