[ACCEPTED]-Create 3 digit Millisecond with php-microtime

Accepted answer
Score: 10

How about something like this?

$mil = 1328910295939;

function toTimestamp($milliseconds)
{
    $seconds = $milliseconds / 1000;
    $remainder = round($seconds - ($seconds >> 0), 3) * 1000;

    return date('Y:m:d H:i:s.', $seconds).$remainder;
}

echo toTimestamp($mil);

Tadaa!

It should 3 be pretty quick too.

Also, this is the output: 2012:02:10 15:44:55.939 - why 2 you're not using - for delimiting the date 1 portion beats me.

Score: 5

Just trim off the last two characters:

substr(date('Y-m-d H:i:s.u',1328910295939), 0, -2)

0

Score: 4

Here's a function that will do it for you 15 accurately (by rounding, not cutting off):

function getTimestamp()
{
        $microtime = floatval(substr((string)microtime(), 1, 8));
        $rounded = round($microtime, 3);
        return date("Y-m-d H:i:s") . substr((string)$rounded, 1, strlen($rounded));
}

Explanation:

microtime() returns 14 2 numbers as 1 string, delimited by a space. the 13 2nd number is the amount of seconds since 12 the unix epoch, and the 1st number is the 11 amount of microseconds since the 2nd number. Basically, the 10 first number is the amount of microseconds 9 expressed in a 8 precision format (0.00000000) and 8 trailing 0s are never cut off.

We round this 7 to a precision of 3 (0.00), and cut off 6 the leading 0, and append that to the actual 5 timestamp.

For some reason the php doc for 4 u, microseconds, doesn't seem to be actually 3 supported. I get 0.000 everytime when using 2 that method. So I resorted to microtime() as 1 a backup solution.

Score: 1
$t = 1328910295939;
echo date('Y-m-d H:i:s.', substr($t, 0, -3)) . substr($t, -3);

Output: 2012-02-10 16:44:55.939 (it depends on the timezone)

0

Score: 0

Because these answers were all quite amusing 5 in their complexity, here's yet another answer for 4 future posterity that uses the asker's original 3 code and doesn't treat numbers as strings.

$mil = 1328910295939;
$seconds = floor($mil / 1000);
$fraction = $mil % 1000;
$showdate = date('Y:m:d H:i:s',$seconds) . ".$fraction";

echo "$mil<br>
$seconds<br>
$fraction<br>
$showdate";

Outputs 2 the following on a server set to the EST 1 time zone:

1328910295939
1328910295
939
2012:02:10 16:44:55.939

More Related questions