PHP validation Determines whether a date is in the correct format

Source: Internet
Author: User
Tags datetime

You can use Strtotime () to convert a date ($date) to a timestamp, and then use Date () in the format you want to validate to a date to verify that the date is the correct format for the $date comparison.

Regular validation 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

/*
* Method IsDate
* function to determine whether the date format is correct
* Parameter $str Date string
$format Date format
* Return None
*/
function Is_date ($str, $format = ' y-m-d ') {
$unixTime _1=strtotime ($STR);
if (!is_numeric ($unixTime _1)) return false; If it is not a number format, it returns directly
$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 not very strict, for 2012-03-00 or 2012-02-31 This format date will return true, I have not found a better solution

The following code verifies that the date is in the form of the 2015-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 that the date format is 2015-08-11, you can change to if (date (' y-m-d ', Strtotime ($date)) = = $date) to determine, verify other formats, and so on.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.