问题
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?
回答1:
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';
回答2:
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:
- Is good practice;
- Makes your customization clear for anyone that works on your project;
- Prevent code breaks if you ever update PHP-AR on your project.
回答3:
The root cause of the issue is that you don't have a default timezone set.
You might see this on local and not the server because the server has the timezone set in the configuration. You can either set this locally in your php configuration or at the top of your source above the requiring of ActiveRecord.php using something like:
date_default_timezone_set('America/New_York');
来源:https://stackoverflow.com/questions/17222180/phpactiverecord-incorrect-datetimeformat