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

Asked

Viewed 829 times

2

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

3 answers

3


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

$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 date is validated this way (taken 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
  • Can you explain this Function better? Normally the format year , has 4 digits.

  • It will validate the format... if the year has 4 digits you change the preg_match preg_match('/ d{4}-d{1,2}-d{1,2}$/', $string)

  • I switched to d{4} and put the following date: 2017-12-30, and changed the d to 4, and gave "It Was Not".

  • The second Function already works! Thanks for the help!

  • I’ll take a look at the first

  • 1

    Ready! I just tidied up the first solution! You can use them together!

Show 1 more comment

2

You can perform a single 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"));

1

Want to work with dates in PHP? Forget it regex or explode of strings or reinvent the wheel to make calculations with dates... Spend a little time studying the Datetime and you’ll see that everything beyond him is a waste of time!

Understand how the date formats in PHP, reflect on what date format you will receive and use the function DateTime::createFromFormat to validate its 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.