phpdatetimestampmilliseconds

Getting date format m-d-Y H:i:s.u from milliseconds


I am trying to get a formatted date, including the microseconds from a UNIX timestamp specified in milliseconds.

The only problem is I keep getting 000000, e.g.

$milliseconds = 1375010774123;
$d = date("m-d-Y H:i:s.u", $milliseconds/1000);
print $d;

07-28-2013 11:26:14.000000


Solution

  • php.net says:

    Microseconds (added in PHP 5.2.2). Note that date() will always generate 000000 since it takes an integer parameter, whereas DateTime::format() does support microseconds if DateTime was created with microseconds.

    So use as simple:

    $micro_date = microtime();
    $date_array = explode(" ",$micro_date);
    $date = date("Y-m-d H:i:s",$date_array[1]);
    echo "Date: $date:" . $date_array[0]."<br>";
    

    Recommended and use dateTime() class from referenced:

    $t = microtime(true);
    $micro = sprintf("%06d",($t - floor($t)) * 1000000);
    $d = new DateTime( date('Y-m-d H:i:s.'.$micro, $t) );
    
    print $d->format("Y-m-d H:i:s.u"); // note at point on "u"
    

    Note u is microseconds (1 seconds = 1000000 µs).

    Another example from php.net:

    $d2=new DateTime("2012-07-08 11:14:15.889342");
    

    Reference of dateTime() on php.net

    I've answered on question as short and simplify to author. Please see for more information to author: getting date format m-d-Y H:i:s.u from milliseconds