如何更改NOW()函数的时区?

3

我正在使用SQL查询中的NOW()函数。我想将其更改为另一个时区。这是否可能?

尝试了以下函数:

class common {

    public function getTime() {
        $date = new DateTime();
        $date->setTimezone(new DateTimeZone('Europe/Paris'));
        return $date->format('Y-m-d H:i:s');
    }

}

并且出现以下错误
Catchable fatal error:  Object of class common could not be converted to string in line below

        $stmt = $this->db->prepare("INSERT INTO `items` 
      (`refno`, `color`, `size`, `qt`, `stackno`, `notes`, `price`, `add_date`)
      VALUES (?, ?, ?, ?, ?, ?, ?, $this->common->getTime())") or die($db->error);

我做错了什么?

MySQL的日期函数不直接处理时区,但是你可以告诉服务器使用哪个时区:http://dev.mysql.com/doc/refman/5.5/en/time-zone-support.html - Marc B
2个回答

3
错误实际上是PHP错误,而不是SQL错误。尝试在字符串插值中评估复杂的变量扩展表达式并不像你所做的那样起作用。请尝试将对象放入大括号 {} 中:
$stmt = $this->db->prepare("INSERT INTO `items` 
      (`refno`, `color`, `size`, `qt`, `stackno`, `notes`, `price`, `add_date`)
      VALUES (?, ?, ?, ?, ?, ?, ?, {$this->common->getTime()})") or die($db->error);

在手册页面http://php.net/manual/en/language.types.string.php中查看子标题复杂(花括号)语法

关于您的评论:

现在在同一行上出现此错误:尝试获取非对象属性

您没有展示如何设置$this->common。根据您展示的语法,common需要是您的类common的对象实例。我猜测您正在尝试调用getTime()函数而没有实例化该类。如果您想使用类的静态方法,您需要这样做:

class common {

    public static function getTime() {
        $date = new DateTime();
        $date->setTimezone(new DateTimeZone('Europe/Paris'));
        return $date->format('Y-m-d H:i:s');
    }

}

$stmt = $this->db->prepare("INSERT INTO `items` 
      (`refno`, `color`, `size`, `qt`, `stackno`, `notes`, `price`, `add_date`)
      VALUES (?, ?, ?, ?, ?, ?, ?, " . common::getTime() . ")") or die($db->error);

如果您不熟悉类和对象之间的区别以及static的用法,那么您需要阅读一些相关内容,例如Object-Oriented PHP

在同一行上现在遇到了以下错误:尝试获取非对象的属性。 - heron
@epic,common 可能没有被实例化。也许你想让 getTime() 成为静态的,这样你就可以像这样调用它:common::getTime() - Marcus Adams
1
谢谢@MarcusAdams!现在我需要一个新的目标。 :) - Bill Karwin

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接