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

前端 未结 23 1493
终归单人心
终归单人心 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:30

    You could also do it like this:

    if (DateTime::createFromFormat('Y-m-d', $date)->format('Y-m-d') === $date) {
    
        // date is correctly formatted and valid, execute some code
    
    }
    

    This will not only check the format, but also the validity of the date self, since DateTime will create only valid dates and this needs to match the input.

提交回复
热议问题