phpdatetimestamptimeago

PHP time ago function returning 4 hours for all dates


I am not sure why, but the following is returning 4 hours ago for all the following date/time

function ago($timestamp){
        $difference = floor((time() - strtotime($timestamp))/86400);
        $periods = array("second", "minute", "hour", "day", "week", "month", "years", "decade");
        $lengths = array("60","60","24","7","4.35","12","10");
        for($j = 0; $difference >= $lengths[$j]; $j++)
            $difference /= $lengths[$j];
        $difference = round($difference);
        if($difference != 1)
            $periods[$j].= "s";
        $text = "$difference $periods[$j] ago";
        return $text;
    }

The dates I am sending is

 "replydate": "29/07/2012CDT04:54:27",
"replydate": "29/07/2012CDT00:20:10",   

Solution

  • Function strtotime is not supporting such format '29/07/2012CDT00:20:10'. Use such syntax '0000-00-00 00:00:00'. And there is no need for 86400. All code:

    function ago($timestamp){
      $difference = time() - strtotime($timestamp);
      $periods = array('second', 'minute', 'hour', 'day', 'week', 'month', 'years', 'decade');
      $lengths = array('60', '60', '24', '7', '4.35', '12', '10');
    
      for($j = 0; $difference >= $lengths[$j]; $j++) $difference /= $lengths[$j];
    
      $difference = round($difference);
      if($difference != 1) $periods[$j] .= "s";
    
      return "$difference $periods[$j] ago";
    }
    
    echo ago('2012-7-29 17:20:28');