2016-02-26 101 views
0

我是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> 
+0

檢查您是否在last_comment ['created_time']中有適當的值; ,, try var:dump(last_comment ['created_time'];); – scaisEdge

+0

我使用相同的代碼來提交created_time。它的波紋管代碼。 $ model-> created_time = Yii :: $ app-> jdate-> date('Y/m/d')。 ' - '。日期( 'H:I:S'); –

+0

您是否嘗試檢查過帳值的內容?結果是什麼? – scaisEdge

回答

0

不幸的是沒有人幫我解決了這個問題,但是我終於得到了有用的功能。 它非常簡單的代碼將時間轉換爲小時,分鐘和...。 你只需要用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'); 
    } 
} 
0

輕鬆就可以使用TIMEAGO jQuery插件Yii2https://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)]); ?> 
1
echo Yii::$app->formatter->asRelativeTime(time()); 
2

對於一個更優雅的畫面中,您可以使用

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

這將爲時間戳顯示

  • 相對日期值小於前一年
  • 時間戳的絕對日期值比一年前更長