【问题标题】:Time Zone Differences in converted timestamp转换时间戳的时区差异
【发布时间】:2011-12-24 23:48:35
【问题描述】:

我找到了这个类,用于将时间戳转换为 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?

标签: php sql datetime timestamp unix-timestamp


【解决方案1】:
        $now = new DateTime('now');

This 请求当地时间。但是你想要UTC时间。 SpecifyUTC 作为构造函数的第二个参数。

【讨论】:

    猜你喜欢
    • 2012-06-03
    • 1970-01-01
    • 2017-07-04
    • 2015-06-27
    • 2011-12-15
    • 2023-03-17
    • 1970-01-01
    • 2021-09-22
    • 2018-12-18
    相关资源
    最近更新 更多