Home > Backend Development > PHP Tutorial > An example of PHP time format verification function

An example of PHP time format verification function

WBOY
Release: 2016-07-25 08:58:07
Original
1053 people have browsed it
This article introduces an example function of PHP to implement time format verification, which is used to check whether the given time is in the correct format. Friends in need can refer to it.

The following code can be used to verify whether the time entered by the user meets the requirements. Example:

<?php
    /**
     * 判断时间格式是否正确
     * @site bbs.it-home.org
     * @param string $param 输入的时间
     * @param string $format 指定的时间格式
     * @return boolean
     */
    function isDatetime($param = '', $format = 'Y-m-d H:i:s')
    {
        return date($format, strtotime($param)) === $param;
    }

    echo "<pre class="brush:php;toolbar:false">";
    $str = "2012-02-30 12:31:22";
    echo $str." - ";
    echo isDatetime($str) ? "TRUE" : "FALSE";
    echo "\n";
    $str = "2012-02-10 12:31:22";
    echo $str." - ";
    echo isDatetime($str) ? "TRUE" : "FALSE";
    echo "\n";
    $str = "2012-02-10";
    echo $str." - ";
    echo isDatetime($str, "Ymd") ? "TRUE" : "FALSE";
    echo "\n";
    $str = "2012-02-10";
    echo $str." - ";
    echo isDatetime($str, "Y-m-d") ? "TRUE" : "FALSE";
?>
Copy after login

Output result:

2012-02-30 12:31:22 - FALSE 2012-02-10 12:31:22 - TRUE 2012-02-10 - FALSE 2012-02-10 - TRUE

Code description: Use strtotime to convert the incoming time into a timestamp, and then use the date function to convert it into the specified format. If the converted string is the same as the incoming string, the format is correct.



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