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 - TRUECode 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. |