时间戳为天、小时、分钟、秒


Timestamp to days, hours, minutes, seconds

如何更改此函数,使其仅打印分钟单位?

我的意思是:

现在是

This was 7 second ago
-- Couple minutes later --
This was 5 minute 8 second ago

但我想要这个:

This was 7 second ago
-- Couple minutes later --
This was 5 minute ago ( i dont care about the seconds )

此外,我如何检查它是否为复数?所以它会在单元后面加一个S?

功能:

function humanTiming($time)
{
$time = time() - $time; // to get the time since that moment
$tokens = array (
    31536000 => 'year',
    2592000 => 'month',
    604800 => 'week',
    86400 => 'day',
    3600 => 'hour',
    60 => 'minute',
    1 => 'second'
);
$result = '';
$counter = 1;
foreach ($tokens as $unit => $text) {
    if ($time < $unit) continue;
    if ($counter > 2) break;
    $numberOfUnits = floor($time / $unit);
    $result .= "$numberOfUnits $text ";
    $time -= $numberOfUnits * $unit;
    ++$counter;
}
return "This was {$result} ago";
}

这里有一种使用DateTime类(函数取自Glavić的答案)的方法:

function human_timing($datetime, $full = false) {
    $now = new DateTime;
    $ago = new DateTime('@'.$datetime);
    $diff = $now->diff($ago);
    $diff->w = floor($diff->d / 7);
    $diff->d -= $diff->w * 7;
    $string = array(
        'y' => 'year',
        'm' => 'month',
        'w' => 'week',
        'd' => 'day',
        'h' => 'hour',
        'i' => 'minute',
        's' => 'second',
    );
    foreach ($string as $k => &$v) {
        if ($diff->$k) {
            $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
        } else {
            unset($string[$k]);
        }
    }
    if (!$full) $string = array_slice($string, 0, 1);
    return $string ? implode(', ', $string) . ' ago' : 'just now';
}

示例:

echo human_timing(time() - 20);
echo human_timing(time() - 1000);
echo human_timing(time() - 5500);

输出:

20 seconds ago
16 minutes ago
1 hour ago

演示

查看PHP Date-Time类,您应该使用它,而不是手动操作。

更换此

$numberOfUnits = floor($time / $unit);

有了这个

$numberOfUnits = floor($time / $unit);
If ( (int) $numberOfUnits > 1 )
{
  $text .= 's';
}

它可能是多的解决方案