How to validate DateTime format?

前端 未结 7 1828
广开言路
广开言路 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:20

    Unless I am remembering incorrectly, the only invalid DateTime format strings are one character long. You can assume any 2 or more character DateTime format string is valid.

    DateTime.ParseExact("qq", "qq", null) == DateTime.Today
    DateTime.ParseExact("myy", "501", null) == "05/01/2001"
    

    Standard (1 character)
    Custom (>1 character)

    For reference, allowed single character strings as formats:

    d,D,f,F,g,G,m,M,o,O,r,R,s,T,u,U,y,Y
    

    Any other character, such as q, by itself is invalid. All other strings will be successfully parsed as formatting strings.

提交回复
热议问题