2015-11-22 154 views
0

我有形式如何用PHP计算两个日期之间的差异?

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

输出不能完全显示。

+1

你尝试过什么?至少尝试一些php的日期时间函数,如果失败了,我们可以帮助你解决失败的代码。 – Terradon

回答

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"); 
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 "; 
相关问题