在 PHP 中,我们经常需要获取当前时间并进行格式化输出。默认的 date 函数只支持精确到秒,然而在某些场景中,比如日志记录、性能监控等,我们需要精确到毫秒的时间输出。本文将介绍如何结合 gettimeofday 和 date 函数,实现带毫秒的时间格式输出。
gettimeofday 是一个获取当前时间的函数,返回的是当前的 Unix 时间戳和微秒数信息。它的返回值可以是数组或浮点数,其中包含秒和微秒。
print_r(gettimeofday());
输出示例:
Array
(
[sec] => 1617181723
[usec] => 123456
[minuteswest] => 0
[dsttime] => 0
)
这里的 sec 是当前秒数,usec 是当前秒内的微秒数。
PHP 的 date 函数可以格式化秒级时间戳,而毫秒部分可以通过 gettimeofday 函数获取。下面是一个简单的示例代码:
<?php
$time = gettimeofday();
$sec = $time['sec']; // 秒数
$usec = $time['usec']; // 微秒数
$milliseconds = floor($usec / 1000); // 将微秒转换为毫秒
// 格式化时间字符串
$formattedTime = date('Y-m-d H:i:s', $sec) . '.' . str_pad($milliseconds, 3, '0', STR_PAD_LEFT);
echo $formattedTime;
?>
输出结果示例:
2025-05-24 15:43:12.123
这里,str_pad 用来保证毫秒数始终是3位数,比如不足3位前面补零。
gettimeofday() 返回当前时间的秒和微秒。
使用 date('Y-m-d H:i:s', $sec) 格式化秒数。
通过除以1000把微秒数转成毫秒数。
使用 str_pad 保证毫秒部分是三位数。
为了方便复用,我们可以封装成一个函数:
<?php
function getCurrentTimeWithMilliseconds() {
$time = gettimeofday();
$sec = $time['sec'];
$usec = $time['usec'];
$milliseconds = floor($usec / 1000);
return date('Y-m-d H:i:s', $sec) . '.' . str_pad($milliseconds, 3, '0', STR_PAD_LEFT);
}
// 使用示例
echo getCurrentTimeWithMilliseconds();
?>
调用 getCurrentTimeWithMilliseconds() 即可得到带毫秒的时间字符串。
通过结合 gettimeofday 和 date 函数,可以轻松实现 PHP 中带毫秒的时间格式输出。该方法不依赖额外扩展,兼容性好,适合用于需要精确时间戳的场景。
<?php
function getCurrentTimeWithMilliseconds() {
$time = gettimeofday();
$sec = $time['sec'];
$usec = $time['usec'];
$milliseconds = floor($usec / 1000);
return date('Y-m-d H:i:s', $sec) . '.' . str_pad($milliseconds, 3, '0', STR_PAD_LEFT);
}
echo getCurrentTimeWithMilliseconds();
?>