如何找到与PHP不同的时间

时间:2014-03-07 18:38:34

标签: php time datediff

我试图找出两次之间的时差。这是我的代码:

$ddtcounter1="2014-03-06 20:20:30";

$ddtcounter2="2014-03-07 21:20:30";

$today = new DateTime($ddtcounter2);
$pastDate = $today->diff(new DateTime($ddtcounter1));

$total= $pastDate->h . ".";
$total2=$total.$pastDate->i;

echo $total2; //echo the time difference in hour.minutes form (Exmple:2.1)

我如何找到时差?我已经阅读了一些指南和教程,但他们没有帮助。我读了很多答案,但它们对我不起作用......

修改 示例(对于谁不理解这个问题):

第一次:{​​{1}}

第二个是:2014-03-06 20:30:30

时差为2014-03-07 19:30:30(23小时),因为它发生在1天前!

1 个答案:

答案 0 :(得分:0)

这应该有效:

$ddtcounter1="2014-03-06 20:15:30";
$ddtcounter2="2014-03-07 21:20:30";

$date1 = new DateTime($ddtcounter1);
$date2 = new DateTime($ddtcounter2);
$diff = $date1->diff($date2);

$hours = $diff->d * 24;
$hours += $diff->h;
echo $hours;
echo $diff->i; // Minutes
echo sprintf('%s.%s', $hours, $diff->i); // Hours.Minutes