Kaka - 1 year ago 130
PHP Question

# Days, hours, minutes since timestamp

So I have this function, which displays how long it's been since a timestamp.

Right now if it's been let's say 60 minutes, it will go over and show "1 hour ago". If it's been 24 hours it goes over to "1 day ago" and so on. How could I do so that if it's been for example 1 hour, show minutes also?

Like

Event occured 58 minutes ago
3 minutes later
Event occured 1 hour 1 minute ago
26 hours later
Event occured 1 day 2 hour ago

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'
);

foreach (\$tokens as \$unit => \$text) {
if (\$time < \$unit) continue;
\$numberOfUnits = floor(\$time / \$unit);
return \$numberOfUnits.\$text.' ago';
}

}

You need to modify your function like this:

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 "{\$result}ago";
}