2015-11-22 155 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 "; 
相關問題