2011-12-20 21 views
2

我有這個課程,我發現將時間戳轉換爲X時間之前。除了一個問題,它工作得很好。我在太平洋時區,所以時間總是在8小時前說,當時應該說是2秒前。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; 
    } 
} 

如何通過SQL插入新行:

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

默認設置爲CURRENT_TIMESTAMP;

我該如何修改我的方法才能使其工作?理想情況下,我希望這對所有人都是普遍的,所以無論您在哪個時區,它都會根據新條目何時存在顯示X時間。

我相信它與UTC有關?

回答

5

如果您構建Cokidoo_DateTime時,該方法__toString()中正確設置你的時區,$now = new DateTime('now');應該從父母得到的時區:

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