时间戳到天,小时,分钟,秒

时间:2013-11-24 07:05:29

标签: php

如何更改此功能以便单独打印分钟单位?

我的意思是:

现在是

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

3 个答案:

答案 0 :(得分:3)

以下是使用DateTime类(从Glavić's answer here获取的函数)执行此操作的一种方法:

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

Demo

答案 1 :(得分:1)

查看PHP Date Time类,您应该使用它而不是手动执行。

答案 2 :(得分:0)

替换此

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

有了这个

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

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

这可能是你的复数解决方案