gpt4 book ai didi

php - 在 PHP 中获取精确时间

转载 作者:行者123 更新时间:2023-12-02 07:57:05 25 4
gpt4 key购买 nike

我注意到,无论给定脚本的执行时间如何,每次 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 ()

关于php - 在 PHP 中获取精确时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/230792/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com