Reputation: 309
How can I check if a variable is a datetime type on php, please? I've tried this, but it seems doesn't work.
public function setRegistrationDate ($registrationDate) {
if (!is_date($registrationDate, "dd/mm/yyyy hh:mm:ss")) {
trigger_error('registrationDate != DateTime', E_USER_WARNING);
return;
}
$this->_registrationDate = $registrationDate;
}
Upvotes: 21
Views: 43589
Reputation: 2349
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) ...
Upvotes: 66
Reputation: 2873
function validateDate($date, $format = 'Y-m-d H:i:s')
{
$d = DateTime::createFromFormat($format, $date);
return $d && $d->format($format) == $date;
}
Reference:
Upvotes: 10
Reputation: 20830
The simplest answer is : to check with strtotime() function
$date = strtotime($datevariable);
If it's valid date, it will return timestamp, otherwise returns FALSE.
Upvotes: 6
Reputation: 18584
I would use the following method:
public function setRegistrationDate ($registrationDate) {
if(!($registrationDate instanceof DateTime)) {
$registrationDate = date_create_from_format("dd/mm/yyyy hh:mm:ss", $registrationDate)
}
if(!($registrationDate instanceof DateTime)) {
trigger_error('registrationDate is not a valid date', E_USER_WARNING);
return false;
}
$this->_registrationDate = $registrationDate;
return true
}
Upvotes: 2