Af_doubts
Af_doubts

Reputation: 55

Check if is a datetime php

I've made this function

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

And it fails on

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

but I can see the error (is not my server).
What changes I have to do to make that function work. If its a datetime, it should return the date ,if not is a datetime returns the data and if its null return a string with 'null' value

Upvotes: 1

Views: 1138

Answers (1)

M. Eriksson
M. Eriksson

Reputation: 13635

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

Upvotes: 1

Related Questions