我注意到,无论给定脚本的执行时间如何,每次 date() 调用都将返回相同的时间戳,无论该函数在脚本中的何处被调用。看起来它只是返回脚本首次开始执行的时间。
出于日志记录的目的,能够从脚本中获取增量时间戳将非常有用。这可能吗?有没有一种相对轻量级的方法可以做到这一点?
编辑 microtime() 的示例功能表明它可能会这样做。谁能证实一下?
更新: microtime() 确实有效,但我无法使用 date() 函数对其进行格式化,因为 date() 只接受时间戳作为整数(因此没有微秒)。如何从 microtime() 返回的值中获取格式正确的日期?
请您参考如下方法:
首先,date()用于格式化时间戳 - 这只是默认行为,当调用 date()
时不带第二个参数,它将使用当前时间戳。使用的时间戳将是调用函数时的时间戳 - 调用 date('Y-m-d')
与调用 date('Y-m-d', time()) 相同
其中 time()会给你
[...] the current time measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).
每次调用 date()
时,您只会获得相同的时间戳,因为您的脚本速度太快,并且在一秒内运行,导致时间戳没有变化。
解决格式化 microtime() 的第二个问题返回值,您可以执行以下操作(未经测试)
function formatTime($microtime, $format)
{
list($timestamp, $fraction) = explode('.', $microtime);
return date($format, (int)$timestamp) . '.' . $fraction;
}
$microtime
的值应该是一个float
,当你将true
作为参数传递给microtime ()