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


当前回答

即使你使用的是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

其他回答

$timeparts = explode(" ",microtime());
$currenttime = bcadd(($timeparts[0]*1000),bcmul($timeparts[1],1000));
echo $currenttime;

注意:该功能需要PHP5,因为 Microtime()和BC数学模块也是必需的(因为我们正在处理 对于较大的数字,可以检查phpinfo中是否有该模块)。

希望这对你有帮助。

简单的回答是:

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

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 

在PHP 5中使用microtime(true),或者在PHP 4中进行以下修改:

array_sum(explode(' ', microtime()));

编写该代码的可移植方法是:

function getMicrotime()
{
    if (version_compare(PHP_VERSION, '5.0.0', '<'))
    {
        return array_sum(explode(' ', microtime()));
    }

    return microtime(true);
}

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

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