What is the MM/DD/YYYY regular expression and how do I use it in php?

后端 未结 9 942
清歌不尽
清歌不尽 2020-12-03 05:11

I found the regular expression for MM/DD/YYYY at http://www.regular-expressions.info/regexbuddy/datemmddyyyy.html but I don\'t think I am using it correctly.

Here\'s

相关标签:
9条回答
  • 2020-12-03 05:31

    Regex of the author of the question is almost correct. Date is not validated because a pattern should be:

      pattern="^(0[1-9]|1[012])[/](0[1-9]|[12][0-9]|3[01])[/](19|20)\d\d$"
    

    or if to be fancy:

      pattern="^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d$"
    

    Please note that this pattern checks only for a format of a date and max/min values for individual date elements. That means a user's entry should be checked for validity of date in JavaScript function and/or a Server (e.g February 29 should not be allowed if a year is not a leap one).

    As a side note, if you would like to allow a single digit (let's say for a month), change a month part to

    ([0-9]|0[1-9]|1[012])
    

    Explanation:
    [0-9] - single digit between 0 and 9
    or
    0[1-9] - two digits between 01 and 09
    or
    1[012] - two digits limited to 10, 11, 12

    0 讨论(0)
  • 2020-12-03 05:42

    Your regex needs delimiters:

    /(0[1-9]|1[012])[- \/.](0[1-9]|[12][0-9]|3[01])[- \/.](19|20)\d\d/

    0 讨论(0)
  • 2020-12-03 05:43

    String timeStamp = "03/11/2018 17:51:45";

    private static Pattern TIMESTAMP_PATTERN = Pattern.compile("(0?[1-9]|1[012])/(0?[1-9]|[1-2][0-9]|3[0-1])/" + "([1-9][0-9]{3}) ([0-1]?[0-9]|2[0-3]):([0-5]?[0-9]):([0-5]?[0-9])");

    private static boolean isTimeStampValid(String timeStamp) {
            boolean isFeb = timeStamp.split("/")[0].matches("(0?[2])");
            if (isFeb) {
                boolean isValidFebDate = timeStamp.split("/")[1].matches("(0?[1-9]|1[1-9]|2[0-8])");
                if (!isValidFebDate) return false;
            }
            return TIMESTAMP_PATTERN.matcher(timeStamp).matches();
        }
    
    0 讨论(0)
提交回复
热议问题