How can I check a php variable is datetime?

I have a php variable that contains a date-time value, for example 2014-05-11 23:10:11

this can change, so I need to find either a date value or not, below is my variable

$my-variable='2014-08-26 18:25:47';

      

+3


source to share


4 answers


This should work for you to check if the date is correct in your format:

<?php

    $date = '2014-08-26 18:25:47';


    function isTime($time) {
        if (preg_match("/^([1-2][0-3]|[01]?[1-9]):([0-5]?[0-9]):([0-5]?[0-9])$/", $time))
            return true;
        return false;
    }

    $parts = explode(" ", $date);
    list($y, $m, $d) = explode("-", $parts[0]);

    if(checkdate($m, $d, $y) && isTime($parts[1]) ){
        echo "OK";
    } else {
        echo "BAD";
    }

?>

      



output:

OK

      

0


source


DateTime

is a class in PHP. You must ask a different question if you want to validate a string. To check an instance DateTime

:



$my_variable instanceof DateTime

      

+1


source


$my_variable='2014-08-26 18:25:47';
...
if ($my_variable instanceof DateTime) {
  ...
}

      

or

if (is_a($my_variable, 'DateTime')) {
  ...
}

      

0


source


If it is a string representing a date in time, you can use date_parse: http://php.net/manual/en/function.date-parse.php This will return an associative array with the datetime string parts, if valid, FALSE. if not.

If it is a date object, see the answer describing instanceOf

.

0


source







All Articles