Verify valid date using PHP's DateTime class

You can try this one:

static public function verifyDate($date)
{
    return (DateTime::createFromFormat('m/d/Y', $date) !== false);
}

This outputs true/false. You could return DateTime object directly:

static public function verifyDate($date)
{
    return DateTime::createFromFormat('m/d/Y', $date);
}

Then you get back a DateTime object or false on failure.

UPDATE:

Thanks to Elvis Ciotti who showed that createFromFormat accepts invalid dates like 45/45/2014. More information on that: https://stackoverflow.com/a/10120725/1948627

I've extended the method with a strict check option:

static public function verifyDate($date, $strict = true)
{
    $dateTime = DateTime::createFromFormat('m/d/Y', $date);
    if ($strict) {
        $errors = DateTime::getLastErrors();
        if (!empty($errors['warning_count'])) {
            return false;
        }
    }
    return $dateTime !== false;
}

With DateTime you can make the shortest date&time validator for all formats.

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

var_dump(validateDate('2012-02-28 12:12:12')); # true
var_dump(validateDate('2012-02-30 12:12:12')); # false

function was copied from this answer or php.net


You could check this resource: http://php.net/manual/en/datetime.getlasterrors.php

The PHP codes states:

try {
    $date = new DateTime('asdfasdf');
} catch (Exception $e) {
    print_r(DateTime::getLastErrors());
    // or
    echo $e->getMessage();
}

Tags:

Datetime

Php