Aaron
Aaron

Reputation: 1966

X Time Ago in PHP

I've got this class I found for converting timestamps to X Time Ago. It works great, except for one problem. I'm in the Pacific Time Zone, and so the time always says 8 hours ago, when it should really say 2 seconds ago.

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

How I insert new rows via SQL:

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

Default is set to CURRENT_TIMESTAMP;

How can I modify my method to get this to work? Ideally, I'd like this to be universal for everyone, so no matter what time zone you're in, it will shows X time ago based on when a new entry is in existence.

I believe it has something to do with UTC?

Upvotes: 2

Views: 963

Answers (2)

Jauzsika
Jauzsika

Reputation: 3251

Set the time zone:

http://www.php.net/manual/en/datetime.settimezone.php

Upvotes: 0

user142162
user142162

Reputation:

If you properly set your time zone when constructing Cokidoo_DateTime, inside the method __toString(), $now = new DateTime('now'); should get the time zone from the parent:

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

Upvotes: 6

Related Questions