我是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
我理解我将String值作为参数,但我不明白如何将其转换为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
答案 0 :(得分:1)
从错误中可以看出,你的convert函数返回的是一个无法被DateTime构造函数解析的字符串。幸运的是,您应该能够使用传递给转换函数的值直接创建DateTime。
$timestamp = new DateTime('20150807080212Z');
$now = new DateTime();
$diff=$now->diff($timestamp);
答案 1 :(得分:0)
$diff = $now->diff(new DateTime($x));
答案 2 :(得分:0)
要将字符串20150807080212Z
转换为DateTime对象,请使用以下函数:
function ldapTimeToDateTime($time)
{
$date_time = new DateTime();
$date_time->setTimestamp(strtotime($time));
return $date_time;
}
答案 3 :(得分:0)
只需
$now = new DateTime();
$x = DateTime::createFromFormat('U', strtotime('20150807080212Z'));
$diff = $now->diff($x);