如何使用PHP计算两个日期之间的差异?

时间:2015-11-22 11:06:16

标签: php date datetime time

我有两个日期格式

Start Date: 2015-11-15 11:40:44pm 
End Date: 2015-11-22 10:50:88am

现在我需要通过以下形式找到这两者之间的区别:

0 years, 0 months, 7 days, 22 hours, 44 mints, 35 sec

我如何在PHP中执行此操作?

我已经尝试过了:

$strStart = date('Y-m-d h:i:s', time() - 3600);
$strEnd   = '2015-11-22 02:45:25';
$dteStart = new DateTime($strStart); 
$dteEnd   = new DateTime($strEnd);
$dteDiff  = $dteStart->diff($dteEnd);
echo $dteDiff->format("%H:%I:%S");

输出:22:53:58

输出未完全显示。

2 个答案:

答案 0 :(得分:1)

$startDate = "2015-11-15 11:40:44pm";
$endDate = "2015-11-22 10:50:48am";  // You had 50:88 here? That's not an existing time

$startEpoch = strtotime($startDate);
$endEpoch = strtotime($endDate);

$difference = $endEpoch - $startEpoch;

上述脚本将开始和结束日期转换为纪元时间(自1970年1月1日00:00:00 GMT以来的秒数)。然后它完成数学并得到它们之间的差异。

由于数年和数月都不是静态值,我还没有在下面的脚本中添加它们

$minute = 60; // A minute in seconds
$hour = $minute * 60; // An hour in seconds
$day = $hour * 24; // A day in seconds

$daycount = 0; // Counts the days
$hourcount = 0; // Counts the hours
$minutecount = 0; // Counts the minutes

while ($difference > $day) { // While the difference is still bigger than a day
    $difference -= $day; // Takes 1 day from the difference
    $daycount += 1; // Add 1 to days
}

// Now it continues with what's left
while ($difference > $hour) { // While the difference is still bigger than an hour
    $difference -= $hour; // Takes 1 hour from the difference
    $hourcount += 1; // Add 1 to hours
}

// Now it continues with what's left
while ($difference > $minute) { // While the difference is still bigger than a minute
    $difference -= $minute; // Takes 1 minute from the difference
    $minutecount += 1; // Add 1 to minutes
}

// What remains are the seconds
echo $daycount . " days ";
echo $hourcount . " hours ";
echo $minutecount . " minutes ";
echo $difference . " seconds ";

答案 1 :(得分:1)

  

现在我需要通过以下形式找到这两者之间的区别:

     

0 years, 0 months, 7 days, 22 hours, 44 mints, 35 sec

这就是你的主要问题,得到这个确切的输出结构?

那么你只需format the DateInterval就可以了:

echo $dteDiff->format("%y years, %m months, %d days, %h hours, %i mints, %s sec");