PHP - 减去时间不返回任何内容


PHP - subtracting time return nothing

我找到了一个来自SC的函数来输出人类可读时间。

5小时,

1小时,5年等

function human_time ($time)
{
    $time = time() - strtotime($time); // to get the time since that moment
    $tokens = array (
        31536000 => 'year',
        2592000 => 'month',
        604800 => 'week',
        86400 => 'day',
        3600 => 'hour',
        60 => 'minute',
        1 => 'second'
    );
    foreach ($tokens as $unit => $text) {
        if ($time < $unit) continue;
        $numberOfUnits = floor($time / $unit);
        return $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'');
    }
}

我有时间串:2013-09-28 20:55:42

当我调用此函数时human_time('2013-09-28 20:55:42')

然后它什么也不返回,为什么?我在上面的函数中添加了strtotime

请告诉我出了什么问题。

这不是现成的代码,而是应该指导您正确的方式:

$then = new DateTime($time); // you might need to format $time using strtotime or other functions depending on the format provided
$now = new DateTime();
$diff = $then->diff($now, true);
echo $diff->format('Your style goes here');

有关更多文档,请参阅日期时间手册,或随时在此处提问。

编辑:链接已修复。

使用示例:

echo time_elapsed_string('2013-05-01 00:22:35');
echo time_elapsed_string('2013-05-01 00:22:35', true);

输出:

4 months ago
4 months, 2 weeks, 3 days, 1 hour, 49 minutes, 15 seconds ago

链接到函数。