php 如何检查变量类型是否为 DateTime

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19396735/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 19:24:52  来源:igfitidea点击:

how can I check if a variable type is DateTime

phpdatetime

提问by rzqr

How can I check if a variable is a datetime type on php, please? I've tried this, but it seems doesn't work.

请问如何检查变量是否是php上的日期时间类型?我试过这个,但它似乎不起作用。

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;
}

采纳答案by Daniele Vrut

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

Reference:

参考:

回答by Hokusai

I think this way is more simple:

我认为这种方式更简单:

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

This expression is true if $myVaris a PHP DateTimeobject.

如果$myVar是 PHPDateTime对象,则此表达式为真。

Since PHP 5, this can be further simplified to:

从 PHP 5 开始,这可以进一步简化为:

if ($myVar instanceof DateTime) ...

回答by Nishu Tayal

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

最简单的答案是:strtotime()函数检查

$date = strtotime($datevariable);

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

如果是有效日期,则返回timestamp,否则返回FALSE

回答by Matteo Tassinari

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
}