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

问题描述:

我想要得到的是非常喜欢time(),而应在毫秒准确:如何在PHP中以毫秒为单位获得当前时间?

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

这有可能在PHP?

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 
+0

如何保留μsecs部分? – ollydbg 2010-11-15 13:32:21

+0

自从PHP 5.2.2以来,'date()'的'u'格式字符已经返回微秒。 http://www.php.net/manual/en/function.date.php – Aether 2010-11-15 13:44:25

+1

@Aether当我输入'echo date('u');'我在PHP 5.3中得到'000000'我做错了什么? – WolfRevoKcats 2010-11-15 13:48:17

使用microtime()函数。

参见手册页面在这里:http://php.net/manual/en/function.microtime.php

[编辑]要获得年/月/日/小时的输出的要求/分/秒/ MS:

尝试是这样的:

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

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

+0

它返回微秒,毫秒不。此外,如果您不作为第一个参数传递true,它会返回'msec sec'字符串。 – ThiefMaster 2010-11-15 13:25:43

+0

手册页给出了使用返回值的例子;这就是为什么我联系到它。 – Spudley 2010-11-15 13:27:31

+0

μsecs很好,但我需要在年/月/日/小时/分钟/秒/毫秒中得到结果... – ollydbg 2010-11-15 13:28:47

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

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

看看PHP的microtime function

+0

但如何获得年/月/日/小时/分钟/秒/毫秒? – ollydbg 2010-11-15 13:28:09

这是我的方式

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