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

其他回答

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

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

用这个: 函数get_millis () { List ($usec, $sec) =爆炸(' ',microtime()); 返回(int) ((int) $sec * 1000 + ((float) $usec * 1000)); }

Bye

在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);
}

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 

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