php date validation

You can use some methods of the DateTime class, which might be handy; namely, DateTime::createFromFormat() in conjunction with DateTime::getLastErrors().

$test_date = '03/22/2010';

$date = DateTime::createFromFormat('m/d/Y', $test_date);
$date_errors = DateTime::getLastErrors();
if ($date_errors['warning_count'] + $date_errors['error_count'] > 0) {
    $errors[] = 'Some useful error message goes here.';
}

This even allows us to see what actually caused the date parsing warnings/errors (look at the warnings and errors arrays in $date_errors).


You could use checkdate. For example, something like this:

$test_date = '03/22/2010';
$test_arr  = explode('/', $test_date);
if (checkdate($test_arr[0], $test_arr[1], $test_arr[2])) {
    // valid date ...
}

A more paranoid approach, that doesn't blindly believe the input:

$test_date = '03/22/2010';
$test_arr  = explode('/', $test_date);
if (count($test_arr) == 3) {
    if (checkdate($test_arr[0], $test_arr[1], $test_arr[2])) {
        // valid date ...
    } else {
        // problem with dates ...
    }
} else {
    // problem with input ...
}

Though checkdate is good, this seems much concise function to validate and also you can give formats. [Source]

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

function was copied from this answer or php.net


The extra ->format() is needed for cases where the date is invalid but createFromFormat still manages to create a DateTime object. For example:

// Gives "2016-11-10 ..." because Thursday falls on Nov 10
DateTime::createFromFormat('D M j Y', 'Thu Nov 9 2016');

// false, Nov 9 is a Wednesday
validateDate('Thu Nov 9 2016', 'D M j Y');