How can I check if a variable is in date format?

2

Well, I want to check if a $ x variable is in the date format (yy-mm-dd), how can I do this with PHP?

    
asked by anonymous 18.02.2017 / 01:24

3 answers

3

With a regular expression like this ( preg_match function link):

$ string="07-12-30";

// para anos com 4 digitos preg_match('/^[0-9]{4}[-][0-9]{1,2}[-][0-9]{1,2}$/', $string)
if (preg_match('/^[0-9]{1,2}[-][0-9]{1,2}[-][0-9]{1,2}$/', $string)) {
  echo "FOI";
}else{
  echo 'Não foi';
}

You can complete your validation by seeing if the date is valid this way (taken from from here ):

function validateDate($date, $format = 'Y-m-d H:i:s')
{
    $d = DateTime::createFromFormat($format, $date);
    return $d && $d->format($format) == $date;
}


var_dump(validateDate("07-12-30","y-m-d"));
var_dump(validateDate("2007-12-30","Y-m-d")); //quatro digitos
    
18.02.2017 / 01:40
1

Want to work with dates in PHP? Forget regex or explode of strings or reinvent the wheel to do calculations with dates ... Spend a little time studying DateTime and you will see that everything else besides it is a waste of time!

Understand how date formats in PHP , reflect on which date format you will receive and use the DateTime::createFromFormat function to validate your date:

$date = DateTime::createFromFormat('y-m-d', '13-02-12'); // $date será válido

$date = DateTime::createFromFormat('y-m-d', '2013-02-12'); // $date será false
    
18.02.2017 / 03:23
1

You can perform a unique function as well. As below:

function checkData($date, $format = 'Y-m-d H:i:s')
{
 if (preg_match('/^[0-9]{1,2}[-][0-9]{1,2}[-][0-9]{1,2}$/', $date)) {
    $d = DateTime::createFromFormat($format, $date);
    return $d && $d->format($format) == $date;
 }
 else{
   return false;
 }
}
$date = "08-11-29";
var_dump(checkDate($date,"y-m-d"));
    
18.02.2017 / 05:10