How to validate DateTime format?

前端 未结 7 1821
广开言路
广开言路 2020-12-11 00:53

I am suppose to let the user enter a DateTime format, but I need to validate it to check if it is acceptable. The user might enter \"yyyy-MM-dd\" and it would be fine, but t

7条回答
  •  借酒劲吻你
    2020-12-11 01:31

    I assume you want to know if the specified format string is valid...

    For this you could round-trip it:

    private bool IsValidDateFormat(string dateFormat)
    {
        try
        {
            String dts=DateTime.Now.ToString(dateFormat, CultureInfo.InvariantCulture);
            DateTime.ParseExact(dts, dateFormat, CultureInfo.InvariantCulture);
            return true;
        }
        catch (Exception)
        {
            return false;
        }
    }
    

提交回复
热议问题