Check if a string is a valid date using DateTime.TryParse

前端 未结 6 1979
梦谈多话
梦谈多话 2020-11-30 05:27

I am using DateTime.TryParse() function to check if a particular string is a valid datetime not depending on any cultures.
To my surprise , the function re

6条回答
  •  温柔的废话
    2020-11-30 05:54

    Basically, I want to check if a particular string contains AT LEAST day(1 through 31 or 01 through 31),month(1 through 12 or 01 through 12) and year(yyyy or yy) in any order, with any date separator , what will be the solution? So, if the value includes any parts of time, it should return true too. I could NOT be able to define a array of format.

    When I was in a similar situation, here is what I did:

    1. Gather all the formats my system is expected to support.
    2. Looked at what is common or can be generalize.
    3. Learned to create REGEX (It is an investment of time initially but pays off once you create one or two on your own). Also do not try to build REGEX for all formats in one go, follow incremental process.
    4. I created REGEX to cover as many format as possible.
    5. For few cases, not to make REGEX extra complex, I covered it through DateTime.Parse() method.
    6. With the combination of both Parse as well as REGEX i was able to validate the input is correct/as expected.

    This http://www.codeproject.com/Articles/13255/Validation-with-Regular-Expressions-Made-Simple was really helpful both for understanding as well as validation the syntax for each format.

    My 2 cents if it helps....

提交回复
热议问题