如何在Yii2中显示人类可读形式的时差(例如2天前)?

时间:2015-12-22 19:19:44

标签: yii2

是否有人知道如何计算通知的日期时间..例如“几个以前”或刚刚像这样:

我希望有人能帮助我解决这个问题:

<li>
    <a href="javascript:;">
        <span class="time">3 mins</span>
        <span class="details">
        <span class="label label-sm label-icon label-danger">
            <i class="fa fa-bolt"></i>
        </span> Server #12 overloaded. </span>
    </a>
</li>

2 个答案:

答案 0 :(得分:9)

build-in formatter相对时间格式一起使用:

<?php echo Yii::$app->formatter->format($timeOfEvent, 'relativeTime') ?>

答案 1 :(得分:2)

您可以使用一个简单的函数来评估两个日期之间的差异,并根据差异的大小(分钟,小时,天,周......)正确格式化它们。

 public function notifyDate($myStartDate) {

 $datediff = $now - $myStartDate;
 if ($datediff < (60*60)) {  // Minutes
   return floor($datediff/(60*60*24)) . " Minutes ago ";
 }
 if ($datediff < (60*60*24)) {  // Hours
   return floor($datediff/(60*60*24)) . " Hours ago ";
 }
 // this  return the number of day
 return  floor($datediff/(60*60*24)) ;

 }

并在通知栏中调用此功能

<li>
     <a href="javascript:;">
          <span class="time"><?php echo notifyDate($myStartDate); ?></span>
               <span class="details">
                   <span class="label label-sm label-icon label-danger">
                        <i class="fa fa-bolt"></i>
                </span> Server #12 overloaded. 
           </span>

      </a>

</li>