Home > Backend Development > PHP Problem > PHP determines whether the date is legal

PHP determines whether the date is legal

王林
Release: 2023-02-24 20:34:01
Original
7645 people have browsed it

PHP determines whether the date is legal

Use strtotime() function to judge:

/**
 * 校验日期格式是否正确
 *
 * @param string $date 日期
 * @param string $formats 需要检验的格式数组
 * @return boolean
 */
function checkDateIsValid($date, $formats = array("Y-m-d", "Y/m/d")) {
    $unixTime = strtotime($date);
    if (!$unixTime) { //strtotime转换不对,日期格式显然不对。
        return false;
    }
    //校验日期的有效性,只要满足其中一个格式就OK
    foreach ($formats as $format) {
        if (date($format, $unixTime) == $date) {
            return true;
        }
    }

    return false;
}
Copy after login

One thing to note: If the required date format is special, even if it is correct If the format cannot be parsed by the strtotime function, this function cannot be used, but this situation should be very rare.

Example:

var_dump(checkDateIsValid("2013-09-10")); //输出true
var_dump(checkDateIsValid("2013-09-ha")); //输出false
var_dump(checkDateIsValid("2012-02-29")); //输出true
var_dump(checkDateIsValid("2013-02-29")); //输出false
Copy after login

Recommended tutorial:PHP video tutorial

The above is the detailed content of PHP determines whether the date is legal. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template