0

For some reason, when I pass my datetime through my function, it brings back "45 years ago" even though the datetime is equal to 2015-01-14 17:27:13.

Here is the code

Function:

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';
        }
    }
}

When I call it, I am calling it with the result from my MySQLI query it appears as "2015-01-14 17:27:13".

Kevin Harrison
  • 335
  • 1
  • 10

2 Answers2

5

Change the first line of your function so you're subtracting seconds from seconds:

$etime = time() - strtotime($ptime);
mopo922
  • 6,293
  • 3
  • 28
  • 31
4

45 years ago is a UNIX timestamp of 0. Check the data you're passing the function to ensure it's valid.

If you're passing the MySQL date string in, time() - '2015-01-14 17:27:13' is equal to about 1421257297 right now because (int)'2015-01-14 17:27:13' turns into 2015.

ceejayoz
  • 176,543
  • 40
  • 303
  • 368