Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP DateTime microseconds always returns 0

Tags:

php

datetime

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?

like image 931
eydelber Avatar asked Oct 04 '08 00:10

eydelber


2 Answers

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); } 
like image 61
eydelber Avatar answered Sep 21 '22 21:09

eydelber


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'); 
like image 28
tr0y Avatar answered Sep 21 '22 21:09

tr0y