Regarding time ago function in PHP

php

(Jason Stanley) #1

Hello, I have a function that I am using in PHP for when a new blog rating is posted and it will show this output

2 minute(s) ago , sdfsdsf says:

with some stars to make it look good. But when I post a new blog rating it always just starts off at 2minutes ago and doesn’t say 1 second ago or anything like that, the rest of it is good, it is just off by 2 minutes, Here is the function

  function timeago($date) {
    $timestamp = strtotime($date);

    $strTime = array("second", "minute", "hour", "day", "month", "year");
    $length = array("60","60","24","30","12", "10");

    $currentTime = time();
    if($currentTime >= $timestamp) {
      $diff = time()- $timestamp;
      $i = 0;
      for(; $diff >= $length[$i] && $i < count($length) - 1; $i++) {
        $diff = $diff / $length[$i];
      }

      $diff = round($diff);
      return $diff . " " . $strTime[$i] . "(s) ago ";
    }
  }

Can anyone tell me what I am doing wrong to make it always start off at 2minutes ago?


(Yassine) #2

I personally couldn’t understand the whole function you got above, why having that $length array in the first place! But nevertheless here is a working function that takes a string date as input, alongside a $full boolean variable, if $full is false, the function will return the short representation of each date part:

function time_elapsed_from_string($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';
}

Hopefully everything above is self explanatory, and easy to modify.

Enjoy!