date_diff() 函数期望第一个参数为 DateTimeInterface 类型,但您传入了一个字符串。

19

它们具有相同的格式:

$date_expire = '2014-08-06 00:00:00';
$date1 = date("Y-m-d G:i:s");
$date2 = date_create($date_expire);

$diff = date_diff($date1, $date2); //this line makes error.

但是我收到了这个错误:

date_diff() 期望参数1为DateTimeInterface类型,但实际传入的是字符串类型

2个回答

58
由于您传递的是字符串,而date_diff函数需要接受datetime对象。
$date_expire = '2014-08-06 00:00:00';    
$date = new DateTime($date_expire);
$now = new DateTime();

echo $date->diff($now)->format("%d days, %h hours and %i minuts");

演示


1
<?php
$todays_date = date("m/d/Y H:i:s"); 

$exp = date("m/d/Y H:i:s", strtotime('+365 days',$todays_date));

// must use the date_create(); function
$int = date_diff(date_create($todays_date), date_create($exp));

// result, Time difference in days.
echo " time difference"." ".$int->format('%a'); 
?>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接