1

I have a timestamp in milliseconds

$update = 1448895141168.

I'm struggling trying to convert that time into a human readable time (ago).

Example, 1 hour 3 minutes ago.


I've tried using this function in my controller

public function time_elapsed_string($ptime)
    {
        $etime = time() - $ptime;

        if ($etime < 1)
        {
            return '0 seconds';
        }

        $a = array( 365 * 24 * 60 * 60  =>  'year',
                     30 * 24 * 60 * 60  =>  'month',
                          24 * 60 * 60  =>  'day',
                               60 * 60  =>  'hour',
                                    60  =>  'minute',
                                     1  =>  'second'
                    );
        $a_plural = array( 'year'   => 'years',
                           'month'  => 'months',
                           'day'    => 'days',
                           'hour'   => 'hours',
                           'minute' => 'minutes',
                           'second' => 'seconds'
                    );

        foreach ($a as $secs => $str)
        {
            $d = $etime / $secs;
            if ($d >= 1)
            {
                $r = round($d);
                return $r . ' ' . ($r > 1 ? $a_plural[$str] : $str) . ' ago';
            }
        }
    }

calling it

        $update = $device->last_updated_utc_in_secs;
        $ptime = date($update);
        dd($this->time_elapsed_string($ptime)); //"0 seconds"

I kept getting 0 second.

halfer
  • 19,824
  • 17
  • 99
  • 186
code-8
  • 54,650
  • 106
  • 352
  • 604

1 Answers1

5

Your problem is here:

$etime = time() - $ptime;

time() always returns the UNIX timestamp which is the seconds elapsed since the Unix Epoch (January 1 1970 00:00:00 GMT). If you subtract a millisecond value (such as 1448895141168) from that, you'll always get something negative (< 0) - so your first if condition kicks in and returns from the method. Just divide your input value by 1000 (milliseconds to seconds) and you're good to go.

Stefan Gehrig
  • 82,642
  • 24
  • 155
  • 189