the Forum

How do you add a time elapsed date based on entry_date in Expression Engine?

Posted on April 6, 2011 by Michael Rosario
Total Posts: 33  |  Join date: 03-12-11

This shows you how to get the feature that shows how many minutes/hours an entry was posted. (ie: posted 23 minutes ago). First, create a snippet in Expression Engine 2.0+, I used {post_date} and the content is below:

<?
$date = "{entry_date}"; 
//The entry date measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).
$ctime = "{current_time format='%Y%m%d'}"; // Formatted Current Time
$etime = "{entry_date format='%Y%m%d'}";  // Formatted Entry Date 
$entrydate = "{entry_date format="%F %j, %Y"}"; // Formatted Entry Date for display

if( $ctime == $etime) {
    echo timeElapse($date)."  ago";
} else {
   echo "on ".$entrydate;
}
?>
I also add this anywhere on the template:


<?
function timeElapse($time)
{

    $time = time() - $time; // to get the time since that moment

    $tokens = array (
        86400 => 'day',
        3600 => 'hour',
        60 => 'minute',
        1 => 'second'
    );

        // This can be expanded to show weeks, months, and years:
        // 31536000 => 'year'
        // 2592000 => 'month'
        // 604800 => 'week'

    foreach ($tokens as $unit => $text) {
        if ($time < $unit) continue;
        $timeCalc = floor($time / $unit);
        return (($timeCalc<2)?'about an':$timeCalc).' '.$text.(($timeCalc>1)?'s':'');  // displays about an hour or # hours

    }

}
?>


This requires the template to have PHP enabled. You can use {posting_date} instead of the {entry_date format=""} this way:

{exp:channel:entries}
   [..]
     {title}
{post_date} [..] {/exp:channel:entries}

Tags: There are no tags for this entry.

3 answers, add yours below

Posted on on May 13, 2011 at 8:58am
by Michael Rosario

Just found a plugin that does the same thing. Awesome!
http://expressionengine.com/archived_forums/viewthread/73265/#363211

 

Posted on on October 2, 2011 at 10:29am
by Caroline

This is an article that makes you think “never tohuhgt of that!”

 

Posted on on December 3, 2011 at 1:04pm
by BlootSido

This makes sense. Thanks! Will use the plugin.

 
add your answers here
comments powered by Disqus