如何在php中减去微时间并用毫秒显示日期?

2022-08-31 00:41:02

如何在php中减去微时间并用毫秒显示日期?

例如:我已设置结束日期和时间

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

然后我有当前日期或开始日期,从微时间转换而来

$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


答案 1

您需要用于开始/结束值,并且仅将其格式化以在末尾显示。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));

注意:这是从微时间返回浮点值并使用浮点算术来简化数学运算,因此由于浮点数舍入问题,您的数字可能会非常轻微,但是无论如何,您最终都会将结果舍入到3位,并且处理器时序的微小波动无论如何都大于浮点错误, 所以这在多个层面上对你来说不是问题。


答案 2

好吧,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;

我认为这应该对你有用。您只需要计算输出格式即可


推荐