2011-12-20 16 views
2

私はタイムスタンプをX Time Agoに変換するためにこのクラスを見つけました。 1つの問題を除いて、うまく動作します。私は太平洋標準時間帯にいるので、時間は常に8時間前と言われています。本当に2秒前です。私はSQLを経由して新しい行を挿入する方法X時間はPHPで

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; 
    } 
} 

mysql_query("INSERT INTO `" . $dbMain . "`.`" . $dbTable . "` (`title`, `date`) VALUES ('$fileTitle', NOW())"); 

デフォルトはCURRENT_TIMESTAMPに設定されています。

これを機能させるには、方法を変更するにはどうすればよいですか?理想的には、私はこれを誰もが普遍的なものにしたいと思っています。タイムゾーンが何であっても、新しいエントリがいつ存在するかに基づいてX時間前に表示されます。

私はUTCと何か関係があると思いますか?方法__toString()内、Cokidoo_DateTimeを構築するときに正しくタイムゾーンを設定した場合

答えて

5

$now = new DateTime('now');は親からタイムゾーンを取得する必要があります。

$now = new DateTime('now', $this->getTimezone());