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


当前回答

正如其他人所述,您可以使用microtime()在时间戳上获得毫秒精度。

从您的评论来看,您似乎希望它是一个高精度的UNIX时间戳。类似于。net世界中的DateTime.Now.Ticks。

你可以使用以下函数来完成:

function millitime() {
  $microtime = microtime();
  $comps = explode(' ', $microtime);

  // Note: Using a string here to prevent loss of precision
  // in case of "overflow" (PHP converts it to a double)
  return sprintf('%d%03d', $comps[1], $comps[0] * 1000);
}

其他回答

即使你使用的是32位PHP,这也是有效的:

list($msec, $sec) = explode(' ', microtime());

$time_milli = $sec.substr($msec, 2, 3); // '1491536422147'
$time_micro = $sec.substr($msec, 2, 6); // '1491536422147300'

注意,这里提供的不是整数,而是字符串。然而,这在许多情况下都很有效,例如在为REST请求构建url时。

如果需要整数,则必须使用64位PHP。

然后你可以重用上面的代码并强制转换为(int):

list($msec, $sec) = explode(' ', microtime());

// these parentheses are mandatory otherwise the precedence is wrong!
//                  ↓                        ↓
$time_milli = (int) ($sec.substr($msec, 2, 3)); // 1491536422147
$time_micro = (int) ($sec.substr($msec, 2, 6)); // 1491536422147300

或者你也可以用一些简单的句子:

$time_milli = (int) round(microtime(true) * 1000);    // 1491536422147
$time_micro = (int) round(microtime(true) * 1000000); // 1491536422147300

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 
$the_date_time = new DateTime($date_string);
$the_date_time_in_ms = ($the_date_time->format('U') * 1000) +
    ($the_date_time->format('u') / 1000);

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

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

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

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

这是我的实现,应该工作在32位以及。

function mstime(){
    $mstime = explode(' ',microtime());
    return $mstime[1].''.(int)($mstime[0]*1000);
}