在PHP 5.2.5中,此代码始终以微秒为单位返回0:
<?php
$dt = new DateTime();
echo $dt->format("Y-m-d\TH:i:s.u") . "\n";
?>
输出:
[root@www1 ~]$ php date_test.php
2008-10-03T20:31:26.000000
[root@www1 ~]$ php date_test.php
2008-10-03T20:31:27.000000
[root@www1 ~]$ php date_test.php
2008-10-03T20:31:27.000000
[root@www1 ~]$ php date_test.php
2008-10-03T20:31:28.000000
有什么想法吗?
发布于 2008-10-04 00:57:22
这似乎是可行的,尽管http://us.php.net/date记录了微秒说明符,但并不真正支持它,这似乎是不合逻辑的:
function getTimestamp()
{
return date("Y-m-d\TH:i:s") . substr((string)microtime(), 1, 8);
}
发布于 2011-07-07 09:19:10
您可以在构造DateTime
对象时指定您的输入包含微秒,并直接使用microtime(true)
作为输入。
不幸的是,如果精确到秒,这将失败,因为在microtime输出中将没有.
;所以在这种情况下使用sprintf
强制它包含.0
:
date_create_from_format(
'U.u', sprintf('%.f', microtime(true))
)->format('Y-m-d\TH:i:s.uO');
或者等效的(更多的OO风格)
DateTime::createFromFormat(
'U.u', sprintf('%.f', microtime(true))
)->format('Y-m-d\TH:i:s.uO');
发布于 2008-10-04 01:31:09
此函数从http://us3.php.net/date中拉出
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('H:i:s.u'); // 19:40:56.78128
你必须实现这个函数才能让"u“正常工作。:\
https://stackoverflow.com/questions/169428
复制相似问题