In PHP development, we will definitely come into contact with the date() function. We have introduced some uses of the PHPdate function before. I believe everyone will use it. This article mainly teaches you how to determine whether the format of a date is correct in PHP.
Idea
You can use strtotime() to convert the date ($date) into a timestamp, and then use date() to convert it into the format that needs to be verified. A date is compared with $date to see if it is the same to verify whether the format of the date is correct.
Regular verification date format
$dateTime=”2010-6-4 00:00:00″; if(preg_match(“/^d{4}-d{2}-d{2} d{2}:d{2}:d{2}$/s”,$dateTime)) { echo “Yes”; }else{ echo “No”; }
Example
/* * 方法 isDate * 功能 判断日期格式是否正确 * 参数 $str 日期字符串 $format 日期格式 * 返回 无 */ function is_Date($str,$format='Y-m-d'){ $unixTime_1=strtotime($str); if(!is_numeric($unixTime_1)) return false; //如果不是数字格式,则直接返回 $checkDate=date($format,$unixTime_1); $unixTime_2=strtotime($checkDate); if($unixTime_1==$unixTime_2){ return true; }else{ return false; } }
Note that the above judgment method is sufficient for general requirements , but it is not very strict. It will also return true for dates in this format such as 2012-03-00 or 2012-02-31. I have not found a better solution
The following code verifies whether the date is 2015 The format of -08-11 20:06:08:
<?php header("Content-type:text/html;charset=utf-8"); $date = '2015-08-11 20:06:08'; if( date('Y-m-d H:i:s', strtotime($date)) == $date ) { echo 'yes'; } else { echo 'no'; } ?>
So to verify whether the date format is 2015-08-11, you can change it to if(date('Y-m-d', strtotime($date) ) == $date ) to determine, verify other formats, and so on.
Although the article seems very short and the method seems simple, it is indeed a very practical small case. Everyone, hurry up and get it!
Related recommendations:
A related question about the PHPdate() function
Do you know the difference between php date and gmdate to obtain the date?
The above is the detailed content of PHP verifies whether the format of a date is correct. For more information, please follow other related articles on the PHP Chinese website!