X时间在PHP中

时间:2011-12-20 18:37:55

标签: php timestamp

我找到了将时间戳转换为X Time Ago的课程。除了一个问题外,它的效果很好。我在太平洋时区,所以时间总是说8小时前,它真的要说2秒前。

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有关?

2 个答案:

答案 0 :(得分:5)

如果您在构建Cokidoo_DateTime时正确设置了时区,则在方法__toString()内,$now = new DateTime('now');应该从父级获取时区:

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

答案 1 :(得分:0)