user1032531 user1032531 - 3 months ago 19
PHP Question

Verify valid date using PHP's DateTime class

Below is how I previously verified dates. I also had my own functions to convert date formats, however, now am using PHP's DateTime class so no longer need them. How should I best verify a valid date using DataTime? Please also let me know whether you think I should be using DataTime in the first place. Thanks

PS. I am using Object oriented style, and not Procedural style.

static public function verifyDate($date)
{
//Given m/d/Y and returns date if valid, else NULL.
$d=explode('/',$date);
return ((isset($d[0])&&isset($d[1])&&isset($d[2]))?(checkdate($d[0],$d[1],$d[2])?$date:NULL):NULL);
}

Answer

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: http://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;
}