Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create 3 digit Millisecond with php

I have 13 digit number and want to create date and time with include milisecond

Example code is like this this is my php script

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

echo "$showdate";

the result is like this 2012:02:10 15:44:55.xxx ===> xxx is 3 digit miliseconds that i want to show up.

and how to include with 3 digit milisecond after H:i:s

Please help me.....

like image 408
Smith Avatar asked Feb 11 '12 18:02

Smith


3 Answers

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 be pretty quick too.

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

like image 155
Westie Avatar answered Oct 17 '22 22:10

Westie


Just trim off the last two characters:

substr(date('Y-m-d H:i:s.u',1328910295939), 0, -2)
like image 5
Jon Grant Avatar answered Oct 17 '22 20:10

Jon Grant


Here's a function that will do it for you 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 2 numbers as 1 string, delimited by a space. the 2nd number is the amount of seconds since the unix epoch, and the 1st number is the amount of microseconds since the 2nd number. Basically, the first number is the amount of microseconds expressed in a 8 precision format (0.00000000) and trailing 0s are never cut off.

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

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

like image 4
Vigrond Avatar answered Oct 17 '22 21:10

Vigrond