this code always returns 0 in PHP 5.2.5 for microseconds:
<?php $dt = new DateTime(); echo $dt->format("Y-m-d\TH:i:s.u") . "\n"; ?>
Output:
[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
Any ideas?
This seems to work, although it seems illogical that http://us.php.net/date documents the microsecond specifier yet doesn't really support it:
function getTimestamp() { return date("Y-m-d\TH:i:s") . substr((string)microtime(), 1, 8); }
You can specify that your input contains microseconds when constructing a DateTime
object, and use microtime(true)
directly as the input.
Unfortunately, this will fail if you hit an exact second, because there will be no .
in the microtime output; so use sprintf
to force it to contain a .0
in that case:
date_create_from_format( 'U.u', sprintf('%.f', microtime(true)) )->format('Y-m-d\TH:i:s.uO');
Or equivalently (more OO-style)
DateTime::createFromFormat( 'U.u', sprintf('%.f', microtime(true)) )->format('Y-m-d\TH:i:s.uO');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With