检查是否是日期时间PHP

时间:2017-06-15 09:19:18

标签: php datetime

我已经完成了这个功能

function checkNullToInsert($data){

        if($data){
            if($data->format('Y-m-d H:i:s')){
                return  "'".$data->format('Y-m-d H:i:s')."'";
            }else{
                return "'".$data."'";
        }
        else {
            return 'NULL'; 
        }
    }

它失败了

  

if($ data-> format('Y-m-d H:i:s')`

但我可以看到错误(不是我的服务器)。
我必须做些什么改变才能使这个功能发挥作用。如果它是一个日期时间,它应该返回日期,如果不是,则datetime返回数据,如果它的null返回一个带有'null'值的字符串

1 个答案:

答案 0 :(得分:0)

Your current code is trying to use any value that validates as truthy as a DateTime instance. Here's the manual about what values are considered true/false: http://php.net/manual/en/types.comparisons.php

First you need to check if the variable is an instance of DateTime. We can do that with the instanceof operator:

function checkNullToInsert($data){
    if ($data){
        // Check if the variable is an instance of DateTime.
        if ($data instanceof DateTime) {
            return  "'".$data->format('Y-m-d H:i:s')."'";
        } else {
            return "'".$data."'";
        } // You were also missing this closing brace
    }
    else {
        return 'NULL'; 
    }
}

Here's the documentation for instanceof: http://php.net/manual/en/internals2.opcodes.instanceof.php