2

I am using the following php function to convert my standard DATETIME result into a facebook style time ago, which shows the number of seconds, minutes and hours, days etc of that date.

Here's my php function:

<?php
function pretty_relative_time($time) {
 if ($time !== intval($time)) { $time = strtotime($time); }
 $d = time() - $time;
 if ($time < strtotime(date('Y-m-d 00:00:00')) - 60*60*24*3) {
 $format = 'F j';
 if (date('Y') !== date('Y', $time)) {
$format .= ", Y";
 }
 return date($format, $time);
 }
 if ($d >= 60*60*24) {
 $day = 'Yesterday';
 if (date('l', time() - 60*60*24) !== date('l', $time)) { $day = date('l', $time); }
 return $day . " at " . date('g:ia', $time);
 }
 if ($d >= 60*60*2) { return intval($d / (60*60)) . " hours ago"; }
 if ($d >= 60*60) { return "about an hour ago"; }
 if ($d >= 60*2) { return intval($d / 60) . " minutes ago"; }
 if ($d >= 60) { return "about a minute ago"; }
 if ($d >= 2) { return intval($d) . " seconds ago"; }
 return "a few seconds ago";
}
?>

And here's where I call the function:

echo pretty_relative_time($row1['date']);

the problem I'm having is the script almost works 100%, however if something is dated within an hour it only ever shows 'about an hour ago' even if I've posted something within a couple of minutes or seconds. Can someone please show me what I am doing wrong? My date is stored as a DATETIME stamp

Kevin Parks
  • 95
  • 2
  • 11

1 Answers1

2

You can use this function its working 100% correct. . .

function Myfunction ($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.(($numberOfUnits>1)?'s':'');
                             }

                        }

And call in this way. .

$time = strtotime($time);

$time = Myfunction($time);
Anil Baweja
  • 150
  • 14