I have a php variable which contain date-time value like 2014-05-11 23:10:11
some times this may change, so i have to find it either it has date-time value or not, below is my variable
$my-variable='2014-08-26 18:25:47';
This should work for you to check if the string is a valid date time 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
$my_variable='2014-08-26 18:25:47';
...
if ($my_variable instanceof DateTime) {
...
}
or
if (is_a($my_variable, 'DateTime')) {
...
}
DateTime
is a class in PHP. You should ask a different question if you want to validate a string. To validate a DateTime
instance:
$my_variable instanceof DateTime
If it's a string representing a date in time, you can use date_parse: http://php.net/manual/en/function.date-parse.php That will return an associative array with the parts of the date and time string if valid, FALSE if not.
If it's a date-time object, see the answer describing instanceOf
.