2012-02-21 84 views
9

如何在毫秒中減去microtime和顯示日期?如何在毫秒中減去microtime和顯示日期以毫秒?

例如:我已經設定結束日期和時間

$endtime = 2012-02-21 10:29:59; 

然後,我有當前日期或轉換來自microtime中開始日期

$starttime = 2012-02-21 10:27:59.452; 

function getTimestamp() 
{ 
     $microtime = floatval(substr((string)microtime(), 1, 8)); 
     $rounded = round($microtime, 3); 
     return date("Y-m-d H:i:s") . substr((string)$rounded, 1, strlen($rounded)); 
} 

echo getTimestamp(); //sample output 2012-02-21 10:27:59.452 

現在我想減去: $ finaldate = $ endtime - $ starttime;

我希望我的輸出是這樣的:00:00:02.452

回答

16

您需要使用microtime的開始/結束值,並且只將其格式化爲在年底顯示。

// Get the start time in microseconds, as a float value 
$starttime = microtime(true); 

/************/ 
/* Do stuff */ 
/************/ 

// Get the difference between start and end in microseconds, as a float value 
$diff = microtime(true) - $starttime; 

// Break the difference into seconds and microseconds 
$sec = intval($diff); 
$micro = $diff - $sec; 

// Format the result as you want it 
// $final will contain something like "00:00:02.452" 
$final = strftime('%T', mktime(0, 0, $sec)) . str_replace('0.', '.', sprintf('%.3f', $micro)); 

注:此爲microtime返回浮點值並使用浮點運算簡化的數學,讓您的數字可能非常稍微偏離由於浮動四捨五入問題,但你四捨五入結果到3位無論如何,無論如何,處理器時序的微小波動都大於浮點錯誤,所以這對於多層次的用戶來說並不是問題。

3

那麼phpmyadmin使用這樣的代碼來計算查詢所花費的時間。它類似於你的要求:

//time before 
list($usec, $sec) = explode(' ',microtime($starttime)); 
$querytime_before = ((float)$usec + (float)$sec); 
/* your code */ 

//time after 
list($usec, $sec) = explode(' ',microtime($endtime)); 
$querytime_after = ((float)$usec + (float)$sec); 
$querytime = $querytime_after - $querytime_before; 

我認爲這應該適合你。你只需要計算你的輸出格式