DateTime::diff()期望参数1为给定字符串的DateTimeInterface


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

我是php新手。

下面是我的代码:
<?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);
?>

这是我得到的错误: PHP Warning: DateTime::diff() expects parameter 1 to be DateTimeInterface, string given in /home/fkpeNb/prog.php on line 16

您甚至可以检查输出,在这里:https://ideone.com/4CSOGH

我明白了,我给了一个字符串值作为参数,但我不明白我如何将其转换为DateTimeInterface,然后做diff()。如果这是一个愚蠢的问题,请原谅。

我甚至还尝试了如下:

$convertedLdapTimeStamp = convertLdapTimeStamp('20150807080212Z');
$x = new DateTime($convertedLdapTimeStamp); // Here String converted to DateTime
$now = new DateTime(); 
$diff=$now->diff($x);
对于上面的代码

,得到如下错误:

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

这是我做的另一个试验: https://ideone.com/EqYyNJ

从错误中可以看到,转换函数返回了一个DateTime构造函数无法解析的字符串。幸运的是,您应该能够使用传递给转换函数的值直接创建DateTime。

$timestamp = new DateTime('20150807080212Z');
$now = new DateTime();
$diff=$now->diff($timestamp);
$diff = $now->diff(new DateTime($x));

Just

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

要将字符串20150807080212Z转换为DateTime对象,请使用以下函数:

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