0

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

}
Kaka
  • 395
  • 2
  • 8
  • 17

6 Answers6

2

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

Check result on codepad.org.

Alexander Yancharuk
  • 13,817
  • 5
  • 55
  • 55
2

PHP 5.2.0 introduced DateTime object, which will provide a better solution for the problem.

I am going to use my answer on another question to show how easy it is, though will slightly edit the code:

$create_time = "2016-08-02 12:35:04";
$current_time="2016-08-02 16:16:02";

$dtCurrent = DateTime::createFromFormat('Y-m-d H:i:s', $current_time);
// to use current timestamp, use the following:
//$dtCurrent = new DateTime();
$dtCreate = DateTime::createFromFormat('Y-m-d H:i:s', $create_time);
$diff = $dtCurrent->diff($dtCreate);

$interval = $diff->format("%y years %m months %d days %h hours %i minutes %s seconds");

$interval will return 0 years 0 months 0 days 3 hours 40 minutes 58 seconds

Let's get rid of those zero values now. Good old regex is pretty much useful here:

$interval = preg_replace('/(^0| 0) (years|months|days|hours|minutes|seconds)/', '', $interval);

In the end we get exactly what we need: 3 hours 40 minutes 58 seconds

Community
  • 1
  • 1
Kevin Kopf
  • 13,327
  • 14
  • 49
  • 66
0

You can find Event occurred time and current time difference using diff. For example see the following code

$time1 = new DateTime('2013-11-21 12:59:00'); // Event occurred time
$time2 = new DateTime(date('Y-m-d H:i:s')); // Current time
$interval = $time1->diff($time2);

echo $interval->y . " Year " .$interval->m . " Month " .$interval->d ." Days ". $interval->h . " Hours, " . $interval->i." Mintues, ".$interval->s." seconds <br/>";
0

You can use a progressive calculation method such as:

$tokens = array (
    31536000 => 'year',
    2592000 => 'month',
    604800 => 'week',
    86400 => 'day',
    3600 => 'hour',
    60 => 'minute',
    1 => 'second'
);

$tokenValues = array();
foreach($tokens as $tokenValue => $tokenName)
{
    if($time > $tokenValue)
    {
        $tokenValues[$tokenName] = floor($time \ $tokenValue);
        $time -= $tikenValue;
    }
    if(count($tokenValues) == 2)
    {
        break;
    }
}

You should then have only 2 items in tokenValues, adapt as you see fit!

Mathieu Dumoulin
  • 12,126
  • 7
  • 43
  • 71
0

I don't have time to explain, but this function works as I tested it. In addition, I add a feature to handle time from the current time and future. If you supply this function with exact current time, it will return 'just now'. If you supply it with time from the past, it will return a string ended with 'ago'. If you supply it with time from the future, it will return a string ended with 'later'. Another feature is automatic singular/plural form for the time unit. Try it yourself!

function timeEllapsedFrom($from) {
  $time = time() - $from;
  $diff = abs($time);
  $tokens = array (
    'year' => 31536000,
    'month' => 2592000,
    'week' => 604800,
    'day' => 86400,
    'hour' => 3600,
    'minute' => 60,
    'second' => 1
  );
  $result = array();
  foreach ($tokens as $id => $length) {
    $value = floor($diff/$length);
    if ($value) $result[] = "$value $id" . ($value > 1 ? 's' : '');
    $diff -= $length*$value;
  }
  if (!count($result)) return 'just now';
  return join(', ', $result) . ($time < 0 ? ' later' : ' ago');
}

You can test it with this code:

echo timeEllapsedFrom(time() - 604800 - 7200 - 480 - 24);

and it will output:

1 week, 2 hours, 8 minutes, 24 seconds ago

Hope it helps!

Choerun Asnawi
  • 181
  • 1
  • 5
0

Using DateTime class. Works with both past and future timestamps, and does correct pluralization when needed:

function elapsedTime($time)
{
    date_default_timezone_set('UTC');
    $given_time = new DateTime("@$time");
    $current_time = new DateTime();
    $diff = $given_time->diff($current_time);
    $timemap = array('y' => 'year',
                     'm' => 'month',
                     'd' => 'day',
                     'h' => 'hour',
                     'i' => 'minute',
                     's' => 'second');
    $timefmt = array();

    foreach ($timemap as $prop => $desc) {
        if ($diff->$prop > 0) {
            $timefmt[] = ($diff->$prop > 1)
                ? "{$diff->$prop} {$desc}s"
                : "{$diff->$prop} $desc";
        }
    }

    return (!$timefmt)
        ? 'just now'
        : ((count($timefmt) > 1)
            ? $diff->format(sprintf('%s and %s',
                implode(', ', array_slice($timefmt, 0, -1)), end($timefmt)))
            : end($timefmt))
            . (($given_time < $current_time) ? ' ago' : ' later');
}

Testing:

var_dump(elapsedTime(strtotime('1987-11-25 11:40')));
# string(69) "25 years, 11 months, 29 days, 17 hours, 50 minutes and 42 seconds ago"
var_dump(elapsedTime(time()));
# string(8) "just now"
var_dump(elapsedTime(strtotime('2013-11-25')));
# string(41) "18 hours, 29 minutes and 18 seconds later"
Paulo Freitas
  • 13,194
  • 14
  • 74
  • 96