PHP Regex to check date is in YYYY-MM-DD format

前端 未结 23 1579
终归单人心
终归单人心 2020-11-27 10:05

I\'m trying to check that dates entered by end users are in the YYYY-MM-DD. Regex has never been my strong point, I keep getting a false return value for the preg_match() I

23条回答
  •  南笙
    南笙 (楼主)
    2020-11-27 10:45

    I know that this is a old question. But I think I have a good solution.

    $date = "2016-02-21";
    $format = "Y-m-d";
    
    if(date($format, strtotime($date)) == date($date)) {
        echo "true";
    } else {
        echo "false";
    }
    

    You can try it. If you change the date to 21.02.2016 the echo is false. And if you change the format after that to d.m.Y the echo is true.

    With this easy code you should be able to check which date-format is used without checking it by the regex.

    Maybe there is a person who will test it on every case. But I think my idea is generally valid. For me it seems logical.

提交回复
热议问题