0

So my current $item['date'] function gets the time and date of the post in this format Y-m-d H:i:s.

I want to display how many minutes was the post posted or if it is more than 24 hours, how many days ago was it posted OR like 0 days and 20 hours ago? something like that

Why doesn't the minus operator work here my code?

My current code:

<p><?php echo date('Y-m-d H:i:s') - $item['date'] ?> minutes ago</p>
user4244510
  • 79
  • 1
  • 8

2 Answers2

0

What you need to do is convert both dates to timestamp first and substract your original post date from current date and reconvert it back to your desired format. As an example see below.

$now = time();
$datePosted = strtotime($item['date']);

$timePassed = $now - $datePosted;

$agoMinutes = $timePassed/60; //this will give you how many minutes passed
$agoHours = $agoMinutes/60; //this will give you how many hours passed
$agoDays = $agoHours/24; // this will give you how many days passed

And so on ...

Php's timestamp gives date in seconds so it is easier to calculate and work on it if you need mathematical operations.

Madcoe
  • 213
  • 1
  • 6
0

I usually use this function. Use it like this time_ago('2014-12-03 16:25:26')

function time_ago($date){
    $retval = NULL;
    $granularity=2;
    $date = strtotime($date);
    $difference = time() - $date;
    $periods = array('decade' => 315360000,
        'year' => 31536000,
        'month' => 2628000,
        'week' => 604800, 
        'day' => 86400,
        'hour' => 3600,
        'minute' => 60,
        'second' => 1);

    foreach ($periods as $key => $value) 
    {
        if ($difference >= $value) 
        {
            $time = round($difference/$value);
            $difference %= $value;
            $retval .= ($retval ? ' ' : '').$time.' ';
            $retval .= (($time > 1) ? $key.'s' : $key);
            $granularity--;
        }
        if ($granularity == '0') { break; }
    }
    return $retval.' ago';      
}
Khawer Zeshan
  • 9,470
  • 6
  • 40
  • 63