2014-02-10 38 views
0

我想在存儲器中存儲兩個小時的操作。我首先轉換爲毫秒,然後轉換爲可讀的內容。它似乎工作,但最後的數字是不正確的。在這個例子中,它給了我1:30:00的差異。有人能解釋爲什麼嗎?從字符串到毫秒並返回

// I have two hours that come from a MySql database and I store in a var: 
$start= "16:00:00"; 
$end= "16:30:00"; 

// I convert to milliseconds and rest: 
$startMili = strtotime($start); 
$endMili = strtotime($end); 
$dif = $endMili - $startMili ; 

// convert to something readable: 
echo "<br><br> diference: "; 
$readable = date("H:i:s", $dif); 
echo $readable; 
+0

的_strtotime_和_DATE_功能意味着絕對時間戳,而不是間隔!額外的小時可能來自您的時區設置(_date_default_timezone_set_)。也許你可以直接在SQL查詢中使用_TIMEDIFF_函數? –

+0

當我嘗試你的代碼時,我得到0:30:00 – Perry

+0

@Perry的正確結果。真奇怪。也許這是Piotr說的時區。我在巴塞羅那。你在哪? – Nrc

回答

1

您還可以使用日期時間,而不是的strtotime

看下面的例子中

$datetime1 = new DateTime($start, new DateTimeZone('Europe/Amsterdam')); 
$datetime2 = new DateTime($end, new DateTimeZone('Europe/Amsterdam')); 
$interval = $datetime1->diff($datetime2); 
echo $interval->format('%H:%i:%s');