【问题标题】:phpActiveRecord Incorrect DateTimeFormatphpActiveRecord 不正确的日期时间格式
【发布时间】:2013-06-20 19:27:47
【问题描述】:

尝试使用 phpActiveRecord 在表中创建记录时,出现以下错误:

Invalid datetime format: 1292 Incorrect datetime value: '2013-06-20 11:59:08 PDT' for column 'created_at'

正在运行的代码:

$new_cart = new QuoteRequest();
$new_cart->status = "cart";
$new_cart->save();

我已经追踪到 phpActiveRecord 中的相关行。 Connection.php 文件第 55-59 行:

/**
 * Database's datetime format
 * @var string
 */
static $datetime_format = 'Y-m-d H:i:s T';

以及使用它的行(Connection.php,第 457-466 行):

/**
 * Return a date time formatted into the database's datetime format.
 *
 * @param DateTime $datetime The DateTime object
 * @return string
 */
public function datetime_to_string($datetime)
{
  return $datetime->format(static::$datetime_format);
}

以及转换值的位置(Table.php 第 394-412 行):

private function &process_data($hash)
{
    if (!$hash)
        return $hash;

    foreach ($hash as $name => &$value)
    {
        if ($value instanceof \DateTime)
        {
            if (isset($this->columns[$name]) && $this->columns[$name]->type == Column::DATE)
                $hash[$name] = $this->conn->date_to_string($value);
            else
                $hash[$name] = $this->conn->datetime_to_string($value);
        }
        else
            $hash[$name] = $value;
    }
    return $hash;
}

我使用的是 MySQL 5.6.10 版,created_at 字段是时间戳。

问题:这里的phpActiveRecord有问题,还是MySQL的问题?

【问题讨论】:

    标签: php mysql phpactiverecord


    【解决方案1】:
    static $datetime_format = 'Y-m-d H:i:s T';
    

    我认为您应该删除 'T'(它为您提供 PDT,即时区缩写),因为它不是时间戳格式的一部分。

    应该是这样的:

    static $datetime_format = 'Y-m-d H:i:s';
    

    【讨论】:

    • 我试过了,它有效;但是相同的代码在实时服务器上运行,这令人困惑。
    • 你确定吗?尝试在将值插入实时服务器之前对其进行 var_dump。
    • 我会在实时服务器上查看。
    • 在实时服务器上,2013-06-20T13:01:17-0700created_at。 PHP版本区别?
    • 刚刚遇到了同样的事情。我的 MySQL 服务器 (5.5.31) 也被 T 阻塞。无需更改 ActiveRecord 的代码,您可以像这样覆盖格式:ActiveRecord\Connection::$datetime_format = 'Y-m-d H:i:s';
    【解决方案2】:

    接受的答案有效;但是,您正在编写包的代码。这意味着每当您在项目中更新 PHP-AR 时,您都会丢失该更改。

    在您的项目上设置 AR 时,更好的方法是在执行时间上覆盖它:

    ActiveRecord\Config::initialize(function($cfg) {
      // [...] Your init config goes here
      ActiveRecord\Connection::$datetime_format = 'Y-m-d H:i:s';
    });
    

    您的初始化配置可能是differ a little,因此请务必根据您的需要进行调整。

    覆盖您的项目而不是更改供应商的核心文件:

    1. 是好的做法;
    2. 让参与您项目的任何人都能清楚地了解您的自定义;
    3. 如果您在项目中更新 PHP-AR,请防止代码中断。

    【讨论】:

    • 此添加导致以下错误:访问未声明的静态属性:ActiveRecord\Connection::$datetime_format
    【解决方案3】:

    问题的根本原因是您没有设置默认时区。

    您可能会在本地而不是服务器上看到这一点,因为服务器在配置中设置了时区。您可以在您的 php 配置中本地设置此设置,也可以在 ActiveRecord.php 要求上方的源代码顶部使用以下内容进行设置:

    date_default_timezone_set('America/New_York');
    

    【讨论】:

    • 不正确。如果使用上述函数设置时区,此问题仍然存在
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-29
    相关资源
    最近更新 更多