2014-03-13 34 views
0

我試圖在開始時間和結束時間使用date_diff。當開始時間是12:59:58而結束時間是01:00:00時,我得到的差異是11:59:58(而不是2秒)。雖然看起來很清楚這裏發生了什麼,我該如何修復它?這對我來說似乎是一個錯誤,但可能是我的一個問題。date_diff 12:59到1:00會產生差不多12小時的差異

這裏是我使用的代碼:

function getGPSData($siteID, $fromDate, $toDate) 
{ 
    global $pdo; 

    $GPSarray = array(); 
    $maxGPS; 
    $minGPS; 
    $avgGPS; 
    $totalGPS=new DateTime("@0",new DateTimeZone("UTC"));//new DateTime("@0"); 
    $totalEvents=0; 

    $query = "SELECT id, siteID, call_type, start_time, end_time FROM call_log WHERE siteID=:siteID AND (start_time BETWEEN :fromDate AND :toDate) AND (end_time BETWEEN :fromDate AND :toDate) AND call_type IN ('LrrpOneTimeReq','LrrpStoreReq','LrrpUseStoredReq')"; 

    $stmt = $pdo->prepare($query); 
    $stmt->bindParam(":siteID", $siteID); 
    $stmt->bindParam(":fromDate", $fromDate); 
    $stmt->bindParam(":toDate", $toDate); 
    $stmt->execute(); 

    foreach ($stmt as $row) 
    { 
      //HERE IS THE DATE_DIFF 
     $timeDiff = date_diff(new DateTime($row['start_time'],new DateTimeZone("UTC")),new DateTime($row['end_time'],new DateTimeZone("UTC")), true); //force absolute 
     //echo $row['id'] . " --- difference between " . $row['start_time'] . " AND " . $row['end_time'] . " is " . $timeDiff->format("%H:%i:%s") . "<br />"; 
     if(!isset($maxGPS) OR dateIntervalInSeconds($timeDiff) > dateIntervalInSeconds($maxGPS)) 
     { $maxGPS = $timeDiff; echo "from " . $row['id'] . " where start=" . $row['start_time'] . " AND end=" . $row['end_time'] . ", maxGPS is now " . $maxGPS->format("%H:%I:%S") . "<br /><br />"; } 
     if(!isset($minGPS) OR dateIntervalInSeconds($timeDiff) < dateIntervalInSeconds($minGPS)) 
      $minGPS = $timeDiff; 
     $totalGPS->add($timeDiff); 
     $totalEvents++; 
    } 

    if($totalEvents!=0) 
    { 
     //$avgGPS=round($totalGPS->getTimestamp()/$totalEvents); 
     $avgGPS = average_time($totalGPS->format("H:i:s"),$totalEvents,0); 
    } 
    else 
    { 
     $avgGPS=0; 
     $maxGPS=new DateInterval('PT0S'); 
     $minGPS=new DateInterval('PT0S'); 
    } 
    //$avgSeconds = new DateInterval("PT" . $avgGPS . "S"); 
    $GPSarray['max'] = $maxGPS->format("%H:%I:%S"); 
    $GPSarray['min'] = $minGPS->format("%H:%I:%S"); 
    $GPSarray['avg'] = $avgGPS;//gmdate("H:i:s",$avgGPS);//$avgSeconds->format("%H:%i:%s"); 
    $GPSarray['total'] = $totalGPS->format("H:i:s"); 
    $GPSarray['events'] = $totalEvents; 

    return $GPSarray; 

} 
+2

想想上午和下午。 –

+3

*我的*時鐘在12:59後更改爲13:00 ... – deceze

+0

是的,我認爲這是代碼中的錯誤,但這是數據未正確插入的錯誤。 – muttley91

回答

1

的問題是,被插入的數據豁免計算AM/PM,因此所有數據將採用1200小時格式,但代碼是把它當作24小時格式。