2012-02-21 85 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; 

我认为这应该适合你。你只需要计算你的输出格式