How to format datetime output with milliseconds or microseconds?

According to http://php.net/manual/en/function.date.php it is possible to use microseconds with date formatting features using ‘u’.

but when I do this:

$time = microtime(true);

$datetime = new DateTime();
$datetime->setTimestamp($time);
$format = $datetime->format('H:i:s u');
var_dump($format);

I always receive 00000 for ‘u’.

What should I be doing here to either get milliseconds or microseconds in my formatted datetime?

Try uppercase U instead of lowercase u

Thanks for the suggestion, but using U only returns the unix timestamp itself, without microseconds given by the results of microtime(true).

DateTime::setTimestamp() does not accept milli/microseconds. the parameter to pass is an integer denoting the UNIX Timestamp.

@ShinVe Post #3
Thanks for the suggestion, but using U only returns the unix timestamp itself, without microseconds given by the results of microtime(true).

http://php.net/manual/en/class.datetime.php
keith tyler dot com ¶

DateTime does not support split seconds (microseconds or milliseconds etc.)
I don't know why this isn't documented.
The class constructor will accept them without complaint, but they are discarded.
There does not appear to be a way to take a string like "2012-07-08 11:14:15.638276" and store it in an objective form in a complete way.

So you cannot do date math on two strings such as:

<?php
$d1=new DateTime("2012-07-08 11:14:15.638276");
$d2=new DateTime("2012-07-08 11:14:15.889342");
$diff=$d2->diff($d1);
print_r( $diff ) ;

/* returns:

DateInterval Object
(
    [y] => 0
    [m] => 0
    [d] => 0
    [h] => 0
    [i] => 0
    [s] => 0
    [invert] => 0
    [days] => 0
)

Looks like you will have to use sprintf() to output the results from date() and microtime() ``` $time = microtime(true); $dFormat = "l jS F, Y - H:i:s"; $mSecs = $time - floor($time); $mSecs = substr($mSecs,1);
echo '<br />$time ==' .$time; 
echo '<br />'; 
echo '<br />' .sprintf('%s%s', date($dFormat), $mSecs ); 

echo

**Output:**
[quote]
$time ==1430803280.2856
Tuesday 5th May, 2015 - 12:21:20.28555011749268
[/quote]
1 Like

Thank you John (and for the example - I was afraid I would have to do something like that!)

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.