show createdAt属性为"上传x小时x分钟前"

时间:2014-04-15 07:47:32

标签: symfony twig

<div class="avatar-details" id="avatar-details{{imageId}}">
    <ul class="details-list">
        <li><b>Votes:</b><span id="image_votes{{imageId}}">{{ imageVotes }}</span></li>
        <li><b>Clicks:</b></li>
        <!--<li><b>Last action:</b><span id="last_user_action{{imageId}}"></span></li> -->
        <li><b>Uploaded</b>: {{ createdAt | date}}</li>
        <li><b>OP:</b><br>{{imageOwner}}</li>
    </ul>
</div>

{{createdAt | date}}返回类似这样的内容&#34; 2014年4月15日09:39&#34; 我需要它来显示图像创建了多少小时/分钟

1 个答案:

答案 0 :(得分:0)

确保createdAt采用unix时间戳格式,然后您可以使用一些基本数学。

可能有助于您这样做的一些链接;
Time Ago Function 链接永远死亡的代码。     

   $now = time();

       $difference     = $now - $time;
       $tense         = "ago";

   for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) {
       $difference /= $lengths[$j];
   }

   $difference = round($difference);

   if($difference != 1) {
       $periods[$j].= "s";
   }

   return "$difference $periods[$j] 'ago' ";
}
?>

function _ago($tm,$rcs = 0) {
   $cur_tm = time(); $dif = $cur_tm-$tm;
   $pds = array('second','minute','hour','day','week','month','year','decade');
   $lngh = array(1,60,3600,86400,604800,2630880,31570560,315705600);
   for($v = sizeof($lngh)-1; ($v >= 0)&&(($no = $dif/$lngh[$v])<=1); $v--); if($v < 0) $v = 0; $_tm = $cur_tm-($dif%$lngh[$v]);

   $no = floor($no); if($no <> 1) $pds[$v] .='s'; $x=sprintf("%d %s ",$no,$pds[$v]);
   if(($rcs == 1)&&($v >= 1)&&(($cur_tm-$_tm) > 0)) $x .= time_ago($_tm);
   return $x;
}

Twitter Like Time Ago 代码的副本(如果链接已经死亡;

<?php
/* Works out the time since the entry post, takes a an argument in unix time (seconds) 
*/
static public function Timesince($original) {
    // array of time period chunks
    $chunks = array(
    array(60 * 60 * 24 * 365 , 'year'),
    array(60 * 60 * 24 * 30 , 'month'),
    array(60 * 60 * 24 * 7, 'week'),
    array(60 * 60 * 24 , 'day'),
    array(60 * 60 , 'hour'),
    array(60 , 'min'),
    array(1 , 'sec'),
    );

    $today = time(); /* Current unix time  */
    $since = $today - $original;

    // $j saves performing the count function each time around the loop
    for ($i = 0, $j = count($chunks); $i < $j; $i++) {

    $seconds = $chunks[$i][0];
    $name = $chunks[$i][1];

    // finding the biggest chunk (if the chunk fits, break)
    if (($count = floor($since / $seconds)) != 0) {
        break;
    }
    }

    $print = ($count == 1) ? '1 '.$name : "$count {$name}s";

    if ($i + 1 < $j) {
    // now getting the second item
    $seconds2 = $chunks[$i + 1][0];
    $name2 = $chunks[$i + 1][1];

    // add second item if its greater than 0
    if (($count2 = floor(($since - ($seconds * $count)) / $seconds2)) != 0) {
        $print .= ($count2 == 1) ? ', 1 '.$name2 : " $count2 {$name2}s";
    }
    }
    return $print;
}