PHP uses strtotime and date functions to determine whether the date is valid code sharing_PHP tutorial

WBOY
Release: 2016-07-13 17:18:20
Original
960 people have browsed it

At first glance, it should be a simple function to determine whether the date is valid, but when you think about it, it is still a bit troublesome, because you need to check both the format and the validity. For example, 2013-02-29, although the format is correct, the date is invalid; and 2012-02-29, the format is correct and valid.

One method can use regularization, but regularization is actually quite troublesome to understand, and using regularization is not very good at testing effectiveness. Here is a method, mainly using strtotime and date functions for verification. Directly access the function:

Copy code The code is as follows:

/**
* Verify whether the date format is correct
*
* @param string $date date
* @param string $formats format array that needs to be checked
* @return boolean
*/
function checkDateIsValid($date, $ formats = array("Y-m-d", "Y/m/d")) {
$unixTime = strtotime($date);
if (!$unixTime) { //strtotime conversion is wrong, the date format is obviously wrong .
return false;
}

//Verify the validity of the date, as long as it meets one of the formats
foreach ($formats as $format) {
if (date($format, $unixTime) == $date) {
             return true;
The code comments explain it in more detail, so I won’t go into details. One thing to note: If the required date format is relatively special, even if it is in the correct format, the strtotime function cannot parse it, so this function cannot be used, but this situation should be very rare.

Some examples:


Copy code

The code is as follows:

var_dump(checkDateIsValid("2013-09-10")); //output true

var_dump(checkDateIsValid("2013-09-ha")); //Output falsevar_dump(checkDateIsValid("2012-02-29")); //Output truevar_dump(checkDateIsValid(" 2013-02-29")); //Output false



http://www.bkjia.com/PHPjc/621665.html

www.bkjia.com
true

http: //www.bkjia.com/PHPjc/621665.html

At first thought, judging whether the date is valid should be a fairly simple function, but it is still a bit troublesome when you think about it. , because it is necessary to check both the format and the validity. For example 2013-02-2...
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!