Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

phpActiveRecord Incorrect DateTimeFormat

When trying to create a record in a table using phpActiveRecord I get the following error:

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

The code that is running:

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

I've tracked this down to the pertinent lines in phpActiveRecord. The file Connection.php, lines 55-59:

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

And the line that uses this (Connection.php, lines 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);
}

And where the value is converted (Table.php lines 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;
}

I am using MySQL version 5.6.10 and the created_at field is a timestamp.

Question: Is there something wrong with phpActiveRecord here, or is it a MySQL problem?

like image 209
silasjmatson Avatar asked Jun 20 '13 19:06

silasjmatson


2 Answers

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

I think you should remove that 'T' (which gives you PDT, i.e. the timezone abbreviation) as it is not part of the timestamp format.

Should be thus:

static $datetime_format = 'Y-m-d H:i:s';
like image 158
silkfire Avatar answered Sep 27 '22 15:09

silkfire


The accepted answer works; however you're writing over the package's code. That means that whenever you update PHP-AR on your project you'll lose that change.

A better approach would be to override it on execution time when setting up AR on your project:

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

Your init config may differ a little, so be sure to adapt it to your need.

Having the override on your project instead of changing the vendor's core files:

  1. Is good practice;
  2. Makes your customization clear for anyone that works on your project;
  3. Prevent code breaks if you ever update PHP-AR on your project.
like image 45
mathielo Avatar answered Sep 27 '22 17:09

mathielo