显示时间如“2分钟前”


show time like " 2 minutes ago"

我是yii2的初学者。我想显示帖子创建的时间。我使用波纹管函数来获取它,但结果只是 0 分钟前。谁能帮我?

<?php
function notifyDate($myStartDate) {
  $now = Yii::$app->jdate->date('Y/m/d') . '- ' . date('H:i:s');
  $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));
}
?>
<?php
  $last_comment = Comment::find()->orderBy(['id' => SORT_DESC])->one();
  $myStartDate = $last_comment['created_time'];
  $now = Yii::$app->jdate->date('Y/m/d') . '-' . date('H:i:s');
?>
<span class="pull-right text-muted small">
    <em><?php echo notifyDate($myStartDate); ?></em>
</span>

为了获得更优雅的显示,您可以使用

echo ( $timestampToDisplay < 60*60*24*365)
    ? Yii::$app->formatter->asRelativeTime($timestampToDisplay )
    : Yii::$app->formatter->asDate($timestampToDisplay );

这将显示

  • 于一年的时间戳的相对日期值
  • 早于一年的时间戳的绝对日期值
echo Yii::$app->formatter->asRelativeTime(time());

不幸的是,这里没有人帮助我解决这个问题,但我终于得到了这个问题的有用功能。 它非常简单的代码将时间转换为小时,分钟和...。你只需要用 crated time 参数调用函数。它返回帖子已提交多长时间。

echo actionGetAgoTime($created_time);

function actionGetAgoTime($created_at) {

    $created_at = time() - $created_at; // to get the time since that moment
    $created_at = ($created_at < 1) ? 1 : $created_at;
    $tokens = array(
        31536000 => Yii::t('app', 'year'),
        2592000 => Yii::t('app', 'month'),
        604800 => Yii::t('app', 'week'),
        86400 => Yii::t('app', 'day'),
        3600 => Yii::t('app', 'hour'),
        60 => Yii::t('app', 'minute'),
        1 => Yii::t('app', 'second')
    );
    foreach ($tokens as $unit => $text) {
        if ($created_at < $unit)
            continue;
        $numberOfUnits = floor($created_at / $unit);
        return $numberOfUnits . ' ' . $text . ' ' . Yii::t('app', 'ago');
    }
}

您可以轻松地将timeagojquery插件用于Yii2:https://github.com/yiidoc/yii2-timeago。请注意,根据问题代码,您使用 Jalali 日历库。要使用时间插件,您需要转换时间公历。我建议您使用时间戳格式保存日期,以及要在模糊形式上显示日期的位置,请使用此插件,如下所示:

// Suppose you pass $comment as an instance of Comment model to your view on controller.
<?= 'yii'timeago'TimeAgo::tag(['timestamp' => date('c', $comment->created_time)]); ?>