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);
}
推荐文章
- 原则-如何打印出真正的sql,而不仅仅是准备好的语句?
- 如何从关联PHP数组中获得第一项?
- PHP/MySQL插入一行然后获取id
- 我如何排序一个多维数组在PHP
- 如何在PHP中截断字符串最接近于一定数量的字符?
- PHP错误:“zip扩展名和unzip命令都没有,跳过。”
- Nginx提供下载。php文件,而不是执行它们
- Json_encode()转义正斜杠
- 如何在PHP中捕获cURL错误
- 如何要求一个分叉与作曲家?
- 如何在php中创建可选参数?
- 在文本文件中创建或写入/追加
- 为什么PHP的json_encode函数转换UTF-8字符串为十六进制实体?
- 如何从一个查询插入多行使用雄辩/流利
- 如何解析unix时间戳到时间。时间