This article mainly talks about using PHP to verify whether the date format is legal. It has certain reference value. Friends in need can learn about it. I hope it can help you.
In back-end development, we often need to verify the legality of the parameters passed in by the front-end. If it is to verify the date parameter, we can verify it through the following method:
/** * 校验日期格式是否合法 * @param string $date * @param array $formats * @return bool */ function isDateValid($date, $formats = array('Y-m-d', 'Y/m/d')) { $unixTime = strtotime($date); if(!$unixTime) { //无法用strtotime转换,说明日期格式非法 return false; } //校验日期合法性,只要满足其中一个格式就可以 foreach ($formats as $format) { if(date($format, $unixTime) == $date) { return true; } } return false; }
Explanation:
Why can’t the time be accurately verified using only the strtotime() function?
Because as long as the date in the correct format can be converted into a timestamp using strtotime(), such as the date 2018-02-31, in fact, logically speaking, this date does not exist, but it can still be converted using the strtotime() function. It is successfully converted into a timestamp, so we need to use date() to convert the timestamp into a standard format, and then compare it with the incoming date. If they are not equal, it means that the incoming date is also illegal.
PHP itself also has a function to check the time<span style="font-family: 微软雅黑, "Microsoft YaHei";">checkdate()</span>
. This function requires three parameters, namely month, day and year. For example, the above date can be detected by calling the checkdate function like this
if(checkdate(2, 31, 2018)) { echo '日期格式正确'; } else { echo '日期格式不正确'; }
Related tutorials:PHP video tutorial
The above is the detailed content of PHP learning to verify the legality of date format? (using strtotime() and date()). For more information, please follow other related articles on the PHP Chinese website!