Correct Regular expressions to match a date

后端 未结 11 625
不知归路
不知归路 2021-01-27 09:50

What is the correct regular expression to use to validate a date like. 2009-10-22 or 2009-01-01 etc. Platform PHP

相关标签:
11条回答
  • 2021-01-27 10:24

    This (from regexplib.com) will match what you want, and perform checks for leap years, days-per-month etc. It's a little more tolerant of separators than you want, but that can be easily fixed. As you can see, it's rather hideous.

    Alternatively (and preferably in my opinion) you may want to simply check for figures in the correct places, and then perform leap year and days-per-month checks in code. Sometimes one regexp isn't so understandable and there's greater clarity in performing the checks in code explicitly (since you can report precisely what's wrong - "only 30 days in November", rather than a "doesn't match pattern" message, which is next to useless)

    0 讨论(0)
  • 2021-01-27 10:24

    If you want something simple that does a little more than just validates format, but doesn't go as far as validating how many days is in the month that is entered, or leap years, you can use this:

    ^(19|20)[0-9]{2}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$
    

    This example allows years 19xx and 20xx

    0 讨论(0)
  • 2021-01-27 10:31
    [0-9]{4}-[0-9]{2}-[0-9]{2}
    

    or

    \d\d\d\d-\d\d-\d\d
    

    or

    ...

    simply read first regex tutorial

    0 讨论(0)
  • 2021-01-27 10:34

    As you have to deal with accepting 2009-02-28 but not 2009-02-29 but accept 2008-02-28 you need more logic that 1 think a regex can give. (But if someone can show it I would be impressed)

    I would try to convert it to a date and report if the conversion failed or if you you language has a check date function use that.

    0 讨论(0)
  • \d{4}-\d{2}-\d{2} would match string in that form, but to check if date is valid, you'd had to break that string to year, month and date (you can use this regexp for that) parts and check each of them.

    You can additionally, make sure that year must start with 1 or 2: [12]\d{3}-\d{2}-\d{2}, and you can also do the same for month and day: [12]\d{3}-[01]\d-[0123]\d (but I would go with the first regexp and compare parts "manually")

    0 讨论(0)
  • 2021-01-27 10:34

    found this on the web tested it with a few dates and looks stable, for dates between 1900 and 2000:

    (19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])
    
    0 讨论(0)
提交回复
热议问题