1

I have this...

$firstDate = $row['date']; // 2013-09-11 18:35:24
$secondDate = date("Y-m-d H:i:s");  

$datetime1 = new DateTime($firstDate);
$datetime2 = new DateTime($secondDate);
$interval  = $datetime1->diff($datetime2);
if($interval->y !== 0) 
{
$elapsed   = $interval->format('%y years ago');
}
else
if($interval->m !== 0) 
{
$elapsed   = $interval->format('%m months ago');
}
else
if($interval->a <= 7 && a >=1) 
{
$elapsed   = $interval->format('%a days ago');
}
else
if($interval->h !== 0) 
{
$elapsed   = $interval->format('%h hours ago');
}
else
if($interval->i !== 0) 
{
$elapsed   = $interval->format('%i minutes ago');
}
else
if($interval->S !== 0) 
{
$elapsed   = $interval->format('%S seconds ago');
}

$elapsed   = str_replace(array('0 years ago', ' 0 months ago', ' 0 days ago',  ' 0 hours ago', ' 0 minutes ago'), '', $elapsed);
$elapsed   = str_replace(array('1 years ago', '1 months ago', '1 days ago',  '1 hours ago', '1 minutes ago'), array('1 year ago', '1 month ago', '1 day ago', '1 hour ago', '1 minute ago'), $elapsed);

This code is supposed take the date in the database and convert into something people understand - 5 days ago, 5 seconds ago. But now a day later, the code seems to be skipping over the day.

I thought it had something to do with using %a instead fo %d but I got an error. What else could be wrong?

Thanks!

Anthony
  • 471
  • 1
  • 5
  • 12

1 Answers1

2

I believe this may be a more elegant solution to your problem:

Modified from PHP How to find the time elapsed since a date time?

echo 'event happened '.humanTiming($row['date']).' 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.(($numberOfUnits>1)?'s':'');
    }

}
Community
  • 1
  • 1
Kenny
  • 1,543
  • 9
  • 16
  • thanks but I'm getting this error Fatal error: Call to undefined function humanTiming() in /home/kronexga/public_html/forums/index.php on line 39 – Anthony Sep 19 '13 at 22:58
  • make sure you place the function outside of any classes, or reference it differently. Its difficult to comment without more context from your code. – Kenny Sep 19 '13 at 23:01