显示时间喜欢" 2分钟前"

时间:2016-02-26 16:42:45

标签: php yii yii2-advanced-app

我是yii2的初学者。我想显示帖子创建的时间。我用bellow函数得到它,但结果只是 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>

4 个答案:

答案 0 :(得分:4)

要获得更优雅的显示效果,您可以使用

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

这将显示

  • 时间戳的相对日期值少于一年
  • 时间戳超过一年的绝对日期值

答案 1 :(得分:3)

echo Yii::$app->formatter->asRelativeTime(time());

答案 2 :(得分:0)

不幸的是,这里没有人帮我解决这个问题,但我终于找到了解决这个问题的有用功能。  它非常简单的代码可以将时间转换为小时,分钟和.... 你只需要用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');
    }
}

答案 3 :(得分:0)

您可以轻松地为Yii2使用timeago jquery插件:https://github.com/yiidoc/yii2-timeago。请注意,根据您的问题代码,您使用Jalali日历库。要使用timeage插件,您需要转换您的时间格里高利历。我建议你用时间戳格式保存日期,并在模糊表格上显示日期,使用这个插件:

// 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)]); ?>