tags:

views:

3410

answers:

5

Hi, 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?

+1  A: 

From http://bugs.php.net/bug.php?id=45554 it would appear that this is the expected result, which I find odd.

Unkwntech
+3  A: 

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);
}
eydelber
By doing separate calls you have a small chance of two time stamps being out of order: eg call date at 1:29:22.999999 and mircotime at 1:29:23.000001. On my server consecutive calls are about 10 us apart.
Lucky
try: list($usec, $sec) = explode(" ", microtime()); return date (date("Y-m-d\TH:i:s", $sec) . $usec;
Lucky
+4  A: 

This function pulled from 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

Very screwy you have to implement this function to get "u" to work... :\

jmccartie
Hi, what about (string)microtime(), 1, 8?
eydelber
A: 

date_create

time: String in a format accepted by strtotime(), defaults to "now".

strtotime

time: The string to parse, according to the GNU » Date Input Formats syntax. Before PHP 5.0.0, microseconds weren't allowed in the time, since PHP 5.0.0 they are allowed but ignored.

scronide
A: 

String in a format accepted by strtotime() It work!