user3815806
user3815806

Reputation: 243

DateTime::diff() expects parameter 1 to be DateTimeInterface, string given

I am new to php.

Below is my code:

<?php

    date_default_timezone_set('Asia/Calcutta'); 

    function convertLdapTimeStamp($timestamp){
        $time = strtotime($timestamp);  
        return date('d M, Y H:i:s A T',$time);
    }

$convertedLdapTimeStamp = convertLdapTimeStamp('20150807080212Z');
$now = new DateTime();

$diff=$now->diff($convertedLdapTimeStamp);

?>

Here is the error I am getting: PHP Warning: DateTime::diff() expects parameter 1 to be DateTimeInterface, string given in /home/fkpeNb/prog.php on line 16

You can even check the output, here: https://ideone.com/4CSOGH

I got to understand that I am giving a String value as a parameter, but I am not understanding how do I convert it to DateTimeInterface and then do diff(). Sorry if its dumb query.

I even still tried as below:

$convertedLdapTimeStamp = convertLdapTimeStamp('20150807080212Z');
$x = new DateTime($convertedLdapTimeStamp); // Here String converted to DateTime
$now = new DateTime(); 

$diff=$now->diff($x);

for above code, getting error as:

PHP Fatal error:  Uncaught exception 'Exception' with message 'DateTime::__construct(): Failed to parse time string (07 Aug, 2015 13:32:12 PM IST) at position 13 (1): Double time specification' in /home/iqPyO4/prog.php:12

Here is another trial I did: https://ideone.com/EqYyNJ

Upvotes: 0

Views: 8643

Answers (4)

vard
vard

Reputation: 4136

To transform your string 20150807080212Z to a DateTime object, use the following function:

function ldapTimeToDateTime($time)
{
    $date_time = new DateTime();
    $date_time->setTimestamp(strtotime($time));
    return $date_time;
}

Upvotes: 0

Federkun
Federkun

Reputation: 36934

Just

$now = new DateTime(); 
$x = DateTime::createFromFormat('U', strtotime('20150807080212Z'));
$diff = $now->diff($x);

Upvotes: 0

Don&#39;t Panic
Don&#39;t Panic

Reputation: 41810

As you can see from the error, your convert function is returning a string that cannot be parsed by the DateTime constructor. Fortunately, you should be able to create a DateTime directly using the value you are passing to your convert function.

$timestamp = new DateTime('20150807080212Z');

$now = new DateTime();

$diff=$now->diff($timestamp);

Upvotes: 1

geggleto
geggleto

Reputation: 2625

$diff = $now->diff(new DateTime($x));

Upvotes: 0

Related Questions