PHP learning to verify the legality of date format? (using strtotime() and date())

little bottle
Release: 2023-04-06 10:08:01
forward
2530 people have browsed it

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; }
Copy after login

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 timecheckdate(). 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 '日期格式不正确'; }
Copy after login

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!

Related labels:
php
source:cnblogs.com
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
Latest Articles by Author
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!