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);
}
其他回答
使用microtime。该函数返回一个以空格分隔的字符串。第一部分是秒的小数部分,第二部分是积分部分。传入true以获得一个数字:
var_dump(microtime()); // string(21) "0.89115400 1283846202"
var_dump(microtime(true)); // float(1283846202.89)
如果使用微时(true),请注意精度损失。
还有gettimeofday,它以整数形式返回微秒部分。
var_dump(gettimeofday());
/*
array(4) {
["sec"]=>
int(1283846202)
["usec"]=>
int(891199)
["minuteswest"]=>
int(-60)
["dsttime"]=>
int(1)
}
*/
即使你使用的是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
简单的回答是:
$milliseconds = floor(microtime(true) * 1000);
正如其他人所述,您可以使用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);
}
我个人使用这个:
public static function formatMicrotimestamp(DateTimeInterface $dateTime): int
{
return (int) substr($dateTime->format('Uu'), 0, 13);
}
推荐文章
- 在PHP单元测试执行期间,如何在CLI中输出?
- 在PHP中使用heredoc的优势是什么?
- PHP中的echo, print和print_r有什么区别?
- 前一个月的Python日期
- 如何将XML转换成PHP数组?
- 如何将对象转换为数组?
- 从IP地址获取位置
- 获取数组值的键名
- HTTPS和SSL3_GET_SERVER_CERTIFICATE:证书验证失败,CA is OK
- PHP -获取bool值,当为false时返回false
- 在foreach中通过引用传递
- 如何触发命令行PHP脚本的XDebug分析器?
- 如何找出如果你使用HTTPS没有$_SERVER['HTTPS']
- 更好的方法检查变量为null或空字符串?
- 当使用Composer的开发/生产开关时,如何正确部署?