Time()是以秒为单位的——有以毫秒为单位的吗?


当前回答

如果你想看到真正的微秒,你需要将php.ini中的精度设置更改为16。

在此之后,microsecond(true)为我提供了1631882476.298437的输出。

所以我认为我需要用余数(298437)除以1000,但实际上,余数是0.298437秒。所以我需要把它乘以1000才能得到正确的结果。

    function get_milliseconds()
    {
        $timestamp = microtime(true);
        return (int)(($timestamp - (int)$timestamp) * 1000);
    }

其他回答

$the_date_time = new DateTime($date_string);
$the_date_time_in_ms = ($the_date_time->format('U') * 1000) +
    ($the_date_time->format('u') / 1000);

简单的回答是:

$milliseconds = floor(microtime(true) * 1000);

字符串变体的最短版本(32位兼容):

$milliseconds = date_create()->format('Uv');

我个人使用这个:

public static function formatMicrotimestamp(DateTimeInterface $dateTime): int
{
    return (int) substr($dateTime->format('Uu'), 0, 13);
}

PHP 5.2.2 <

$d = new DateTime();
echo $d->format("Y-m-d H:i:s.u"); // u : Microseconds

PHP 7.0.0 < 7.1

$d = new DateTime();
echo $d->format("Y-m-d H:i:s.v"); // v : Milliseconds