PHP DateTime microseconds always returns 0

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');

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... :\