2012-05-23 51 views
2

如何計算考慮PHP中datestamp的持續時間?我在日期之間使用的日期格式爲「Y-m-d H:i:s」,考慮PHP中的日期計算持續時間

我的工作代碼只能計算不考慮日期的時間間隔。下面

是我的代碼:

$assigned_time = "2012-05-21 22:02:00"; 
$completed_time= "2012-05-22 05:02:00"; 

function hmsDiff ($assigned_time, $completed_time) { 
    $assigned_seconds = hmsToSeconds($assigned_time); 
    $completed_seconds = hmsToSeconds($completed_time); 

    $remaining_seconds = $assigned_seconds - $completed_seconds; 

    return secondsToHMS($remaining_seconds); 
} 
function hmsToSeconds ($hms) { 
    $total_seconds = 0; 
    list($hours, $minutes, $seconds) = explode(":", $hms); 
    $total_seconds += $hours * 60 * 60; 
    $total_seconds += $minutes * 60; 
    $total_seconds += $seconds; 

    return $total_seconds; 
} 

function secondsToHMS ($seconds) { 
    $minutes = (int)($seconds/60); 
    $seconds = $seconds % 60; 
    $hours = (int)($minutes/60); 
    $minutes = $minutes % 60; 

    return sprintf("%02d", abs($hours)) . ":" . 
     sprintf("%02d", abs($minutes)) . ":" . 
     sprintf("%02d", abs($seconds)); 

} 

回答

4

的日期時間有一個「差異」方法,它返回的時間間隔對象。間隔對象有一個方法"format" which allows you to customize the output

#!/usr/bin/env php 
<?php 

$assigned_time = "2012-05-21 22:02:00"; 
$completed_time= "2012-05-22 05:02:00"; 

$d1 = new DateTime($assigned_time); 
$d2 = new DateTime($completed_time); 
$interval = $d2->diff($d1); 

echo $interval->format('%d days, %H hours, %I minutes, %S seconds'); 

注意:如果你不使用5.3.0+,有一個很好的答案在這裏:https://stackoverflow.com/a/676828/128346

+0

感謝wilmoore,它可以在我的本地服務器上運行,因爲我使用的是php 5.3,但是在我的在線服務器上它是5.2,在php 5.2環境中可以使用這個選項嗎? – jalf

+0

以下似乎是一個很好的答案:http://stackoverflow.com/a/676828/128346 –

1

不完全知道你想要什麼,什麼是這樣的:

// prevents php error 
date_default_timezone_set ('US/Eastern'); 
// convert to time in seconds 
$assigned_seconds = strtotime ($assigned_time); 
$completed_seconds = strtotime ($completed_time); 

$duration = $completed_seconds - $assigned_seconds; 

// j gives days 
$time = date ('j g:i:s', $duration);