how can I check if a variable type is DateTime

The simplest answer is : to check with strtotime() function

$date = strtotime($datevariable);

If it's valid date, it will return timestamp, otherwise returns FALSE.


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

Reference:

  • http://www.php.net/manual/en/function.checkdate.php#113205
  • https://stackoverflow.com/a/12323025/67332

I think this way is more simple:

if (is_a($myVar, 'DateTime')) ...

This expression is true if $myVar is a PHP DateTime object.

Since PHP 5, this can be further simplified to:

if ($myVar instanceof DateTime) ...

Tags:

Datetime

Php