时间前函数PHP不起作用


Time Ago Function PHP Not Working?

出于

某种原因,当我通过函数传递日期时间时,即使日期时间等于 2015-01-14 17:27:13,它也会带回"45 年前"。

这是代码

功能:

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';
        }
    }
}
当我调用它

时,我正在使用MySQLI查询的结果调用它,它显示为"2015-01-14 17:27:13"。

更改函数的第一行,以便从秒中减去秒:

$etime = time() - strtotime($ptime);

45 年前的 UNIX 时间戳为 0。检查要传递函数的数据以确保其有效。

如果要传入MySQL日期字符串,则time() - '2015-01-14 17:27:13'等于现在大约1421257297,因为(int)'2015-01-14 17:27:13'会变成2015