2012-12-02 38 views
1

我需要確定我們網站上發佈的評論的「時間前」時間戳。我的老闆希望它只顯示幾個小時。所以它應該顯示「48小時前」而不是「2天前」或480小時而不是「20天前」。PHP時間戳直到「小時前」出現問題

這裏是我找到的代碼,但我不知道如何去做,直到小時。

date_default_timezone_set('Asia/Taipei'); 
class Cokidoo_DateTime extends DateTime { 

    protected $strings = array(
     'y' => array('1 year ago', '%d years ago'), 
     'm' => array('1 month ago', '%d months ago'), 
     'd' => array('1 day ago', '%d days ago'), 
     'h' => array('1 hour ago', '%d hours ago'), 
     'i' => array('1 minute ago', '%d minutes ago'), 
     's' => array('now', '%d secons ago'), 
    ); 

    /** 
    * Returns the difference from the current time in the format X time ago 
    * @return string 
    */ 
    public function __toString() { 
     $now = new DateTime('now'); 
     $diff = $this->diff($now); 

     foreach($this->strings as $key => $value){ 
      if(($text = $this->getDiffText($key, $diff))){ 
       return $text; 
      } 
     } 
     return ''; 
    } 

    /** 
    * Try to construct the time diff text with the specified interval key 
    * @param string $intervalKey A value of: [y,m,d,h,i,s] 
    * @param DateInterval $diff 
    * @return string|null 
    */ 
    protected function getDiffText($intervalKey, $diff){ 
     $pluralKey = 1; 
     $value = $diff->$intervalKey; 
     if($value > 0){ 
     if($value < 2){ 
      $pluralKey = 0; 
      } 
      return sprintf($this->strings[$intervalKey][$pluralKey], $value); 
     } 
     return null; 
    } 
} 
echo $date = new Cokidoo_Datetime('2012-11-28 0:59:44'); 

回答

0

如果有發佈日期的時間戳記,它是(或可以是)表示爲INT

$now = time(); //current Unix timestamp in seconds 
$hours = ceil(($now - $posted_time)/3600) 
0
在__toString()的簡單的方式來適應上述代碼中,取代的foreach塊

$hours = $diff->format('h'); 
return $hours > 1 ? $hours . ' hour ago' : $hours . ' hours ago'; 
0

工作例如:您的類修改,以返回幾個小時的差異。

<?php 
class Cokidoo_DateTime extends DateTime { 
    public function __toString() { 
     $now = new DateTime('now'); 
     $diff = $this->diff($now);   
     return $this->getHours($diff); 
    } 

    function getHours($diff) { 
     $hours = ($diff->d * 24) + $diff->h; 
     return (string)$hours; 
    } 
} 
echo $date = new Cokidoo_Datetime('2012-11-28 0:59:44'); 
?> 
0
'd' => array('24 hours ago', '%d hours ago'), 

protected function getDiffText($intervalKey, $diff){ 
     $pluralKey = 1; 
     $value = $diff->$intervalKey; 
     if($value > 0){ 
     if($value < 2){ 
      $pluralKey = 0; 
      } 
      if($intervalKey == "d") 
      { 
      return sprintf($this->strings[$intervalKey][$pluralKey], $value*24); 
      } 
      return sprintf($this->strings[$intervalKey][$pluralKey], $value); 
     } 
    return null; 
} 

}