PhpActiveRecord Invalid DateTimeFormat

When I try 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'

Executable code:

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

I traced this to the corresponding lines in phpActiveRecord. Connection.php file, lines 55-59:

 /** * Database datetime format * @var string */ static $datetime_format = 'Ymd H:i:s T'; 

And the line that uses this (Connection.php, lines 457-466):

 /** * Return a date time formatted into the database 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 rows 394-412 tables):

 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 something wrong with phpActiveRecord here, or is it a MySQL problem?

+4
source share
3 answers
 static $datetime_format = 'Ymd H:i:s T'; 

I think you should remove this 'T' (which gives you PDT , i.e. shortening the time zone paragraph), since it is not part of the timestamp format.

It should be this way:

 static $datetime_format = 'Ymd H:i:s'; 
+6
source

The accepted answer works; however you write over the package code. This means that whenever you update PHP-AR in your project, you will lose this change.

A better approach would be to override it at runtime when setting up AR in your project:

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

Your init configuration may vary slightly , so be sure to adapt it to your needs.

The presence of an override in the project instead of changing the main supplier files:

  • Good practice;
  • Makes your setup understandable to everyone who works on your project;
  • Prevent code breaking if you ever upgrade PHP-AR in your project.
+2
source

The root cause of the problem is that you do not have a default time zone.

You can see this on the local, not on the server, because the server has a time zone set in the configuration. You can install this locally in your php configuration or at the top of your source above the required ActiveRecord.php, using something like:

 date_default_timezone_set('America/New_York'); 
-1
source

Source: https://habr.com/ru/post/1487359/


All Articles