-2

How could I alter this function so it prints the minutes unit alone?

What I mean is:

Right now it's

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

But I want this:

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

Also how could I check if its plural? So it will ad an S after the unit?

The function:

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";
}
Kaka
  • 395
  • 2
  • 8
  • 17

3 Answers3

3

Here's one way to do it using DateTime class (function taken from 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';
}

Examples:

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

Output:

20 seconds ago
16 minutes ago
1 hour ago

Demo

Community
  • 1
  • 1
Amal Murali
  • 75,622
  • 18
  • 128
  • 150
1

Check out PHP Date Time class, you should be using this instead of doing things manually.

Unihedron
  • 10,902
  • 13
  • 62
  • 72
ddoor
  • 5,819
  • 9
  • 34
  • 41
0

Replace this

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

With this

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

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

It may be your solution for plural

Vaclav Kusak
  • 124
  • 1
  • 7