Calculate How Long Ago With Timestamp And PHP

November 7, 2017 by Andreas Wik

You know how YouTube shows the date the video was published as “X hours ago”, “Y days ago” and “Z years ago” etc, rather than 2017-01-22 for example. This handy function time_ago() takes a Unix timestamp and turns it into a how-long-ago string.

function time_ago($timestamp)
{
    $etime = time() - $timestamp;
 
    if ($etime < 1)
    {
        return '0 seconds';
    }
 
    $a = array(12 * 30 * 24 * 60 * 60  =>  'year', 30 * 24 * 60 * 60 => 'month', 24 * 60 * 60 => 'day', 60 * 60 => 'hour', 60 => 'minute', 1 => 'second');
 
    foreach ($a as $secs => $str)
    {
        $d = $etime / $secs;
        if ($d >= 1)
        {
            $r = round($d);
            return $r . ' ' . $str . ($r > 1 ? 's' : '') . ' ago';
        }
    }
}

 

Let’s call it.

$now = time();
$five_mins_ago = time_ago($now - 300);
$five_days_ago = time_ago($now - 432000);
$five_months_ago  = time_ago($now - 12960000);
$one_year_ago = time_ago($now - 31556952);
 
echo '<p>' . $five_mins_ago . '</p>';
echo '<p>' . $five_days_ago . '</p>';
echo '<p>' . $five_months_ago . '</p>';
echo '<p>' . $one_year_ago . '</p>';

 

Turn YYYY-MM-DD into Timestamp

In case the date we use is in the format YYYY-MM-DD for example, we could use the strtotime() function to turn it into a timestamp.

$published_date = '2017-01-31';
$timestamp = strtotime($published_date);

 

Final Code

// Turn date YYYY-MM-DD into timestamp
$published_date = '2017-01-31';
$published_timestamp = strtotime($published_date);
 
echo '<p>' . $published_date . ' was ' . time_ago($published_timestamp) . '<p>';
 
$now = time();
$five_mins_ago = time_ago($now - 300);
$five_days_ago = time_ago($now - 432000);
 
// Output: Published 5 minutes ago
echo '<p>Published ' . $five_mins_ago . '</p>';
 
// Output: Published 5 days ago
echo '<p>Published ' . $five_days_ago . '</p>';
 
function time_ago($timestamp)
{
    $etime = time() - $timestamp;
 
    if ($etime < 1)
    {
        return 'just now';
    }
 
    $a = array(12 * 30 * 24 * 60 * 60  =>  'year', 30 * 24 * 60 * 60 => 'month', 24 * 60 * 60 => 'day', 60 * 60 => 'hour', 60 => 'minute', 1 => 'second');
 
    foreach ($a as $secs => $str)
    {
        $d = $etime / $secs;
        if ($d >= 1)
        {
            $r = round($d);
            return $r . ' ' . $str . ($r > 1 ? 's' : '') . ' ago';
        }
    }
}

 

Share this article

Recommended articles

@awikio