Correctly determine if the date string is a valid date in that format

How do I use PHP to get the current year?
Convert timestamp to readable date/time PHP

You will find the solution to the problem statement: take a string such as 2013-13-01 and tell if it is a valid date or not for the format yyyy-mm-dd?

Solution 1

You can use DateTime::createFromFormat() for this purpose:

function validateDate($date, $format = 'Y-m-d')
{
    $d = DateTime::createFromFormat($format, $date);
    // The Y ( 4 digits year ) returns TRUE for any integer with any number of digits so changing the comparison from == to === fixes the issue.
    return $d && $d->format($format) === $date;
}
var_dump(validateDate('2013-13-01'));  // false
var_dump(validateDate('20132-13-01')); // false
var_dump(validateDate('2013-11-32'));  // false
var_dump(validateDate('2012-2-25'));   // false
var_dump(validateDate('2013-12-01'));  // true
var_dump(validateDate('1970-12-01'));  // true
var_dump(validateDate('2012-02-29'));  // true
var_dump(validateDate('2012', 'Y'));   // true
var_dump(validateDate('12012', 'Y'));  // false

solution 2

Use in a simple way with PHP prebuilt function:

function checkmydate($date) {
  $tempDate = explode('-', $date);
  // checkdate(month, day, year)
  return checkdate($tempDate[1], $tempDate[2], $tempDate[0]);
}

https://stackoverflow.com/questions/19271381/correctly-determine-if-date-string-is-a-valid-date-in-that-format

How do I use PHP to get the current year?
Convert timestamp to readable date/time PHP

Stay up-to-date about PHP!

We don’t spam!

en English
X
Scroll to Top