Question

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",   
Was it helpful?

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

OTHER TIPS

Rather than writing your own date/time functions, you would be better off using a standard implementation like PHP's DateTime class. There are subtleties to getting time calculations correct, such as time zones and daylight savings.

<?php
    date_default_timezone_set('Australia/Melbourne');

    // Ideally this would use one of the predefined formats like ISO-8601
    //   www.php.net/manual/en/class.datetime.php#datetime.constants.iso8601 
    $replydate_string = "29/07/2012T04:54:27";

    // Parse custom date format similar to original question
    $replydate = DateTime::createFromFormat('d/m/Y\TH:i:s', $replydate_string);

    // Calculate DateInterval (www.php.net/manual/en/class.dateinterval.php)
    $diff = $replydate->diff(new DateTime());

    printf("About %d hour%s and %d minute%s ago\n",
        $diff->h, $diff->h == 1 ? '' : 's',
        $diff->i, $diff->i == 1 ? '' : 's'
    );
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top