php 如何在PHP中以毫秒为单位获取当前时间?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4184769/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 12:13:27  来源:igfitidea点击:

How to get current time in ms in PHP?

phptime

提问by ollydbg

What I want to get is the very like time(),but should be accurate in ms:

我想要得到的是非常像time(),但应该在毫秒中准确:

2010-11-15 21:21:00:987

Is that possible in PHP?

这在 PHP 中可能吗?

回答by WolfRevoKcats

function udate($format, $utimestamp = null) {
  if (is_null($utimestamp))
    $utimestamp = microtime(true);

  $timestamp = floor($utimestamp);
  $milliseconds = round(($utimestamp - $timestamp) * 1000000);

  return date(preg_replace('`(?<!\\)u`', $milliseconds, $format), $timestamp);
}

echo udate('Y-m-d H:i:s:u'); // 2010-11-15 21:21:00:987

回答by ThiefMaster

Use microtimeand convert it to milliseconds:

使用microtime中,并将其转换为毫秒:

$millitime = round(microtime(true) * 1000);

回答by Spudley

Use the microtime()function.

使用该microtime()功能。

See the manual page here: http://php.net/manual/en/function.microtime.php

请参阅此处的手册页:http: //php.net/manual/en/function.microtime.php

[EDIT] To get the output in year/month/day/hour/minutes/seconds/ms as requested:

[编辑] 要按要求以年/月/日/小时/分钟/秒/毫秒为单位获取输出:

Try something like this:

尝试这样的事情:

list($usec, $sec) = explode(" ", microtime());
$output = date('Y/m/d H:i:s',$sec). " /" . $usec;

Again, see the manual page for more details on how microtime()works.

同样,请参阅手册页以了解有关如何microtime()工作的更多详细信息。

回答by Thinh Phan

This is my way

这是我的方式

list($usec, $sec) = explode(" ", microtime());
$time =  date("Y-m-d H:i:s:",$sec).intval(round($usec*1000));
echo $time;

回答by RedHotPawn.com

Since PHP 7.3 hrtimehas been available.

自 PHP 7.3hrtime可用以来。

This means you can use high resolution timers in nanoseconds without any of the issues of microtime. (e.g. System clock changing between tests)

这意味着您可以在纳秒内使用高分辨率计时器,而不会出现任何微时间问题。(例如系统时钟在测试之间变化)

So, you can now get ms reliably on 64bit platforms with :

因此,您现在可以通过以下方式在 64 位平台上可靠地获得 ms:

intval( hrtime(true) / 1000000 ); //Convert nanosecond to ms

Format as described in earlier answers.

格式如先前答案中所述。

回答by nnevala

Take a look at php's microtime function.

看看php的microtime函数