显示时间像“2分钟前”
问题描述:
我是yii2的初学者。我想显示帖子创建多久之前。我用波纹管功能得到它,但结果只是0分钟前。谁能帮我?显示时间像“2分钟前”
<?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>
答
不幸的是没有人帮我解决了这个问题,但是我终于得到了有用的功能。 它非常简单的代码将时间转换为小时,分钟和...。 你只需要用crated时间参数调用函数。并返回该帖子已提交多长时间。
echo actionGetAgoTime($ created_time);
功能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');
}
}
答
轻松就可以使用TIMEAGO jQuery插件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)]); ?>
答
echo Yii::$app->formatter->asRelativeTime(time());
答
对于一个更优雅的画面中,您可以使用
echo ($timestampToDisplay < 60*60*24*365)
? Yii::$app->formatter->asRelativeTime($timestampToDisplay)
: Yii::$app->formatter->asDate($timestampToDisplay);
这将为时间戳显示
- 相对日期值小于前一年
- 时间戳的绝对日期值比一年前更长
检查您是否在last_comment ['created_time']中有适当的值; ,, try var:dump(last_comment ['created_time'];); – scaisEdge
我使用相同的代码来提交created_time。它的波纹管代码。 $ model-> created_time = Yii :: $ app-> jdate-> date('Y/m/d')。 ' - '。日期( 'H:I:S'); –
您是否尝试检查过帐值的内容?结果是什么? – scaisEdge