Skip to content

Commit

Permalink
Fix toDatabase() to work with non-DateTimeImmutable properly
Browse files Browse the repository at this point in the history
  • Loading branch information
chinpei215 committed Apr 2, 2018
1 parent 7037d74 commit c5f27f3
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/Database/Type/DateTimeType.php
Expand Up @@ -18,6 +18,7 @@
use Cake\Database\Type;
use Cake\Database\TypeInterface;
use Cake\Database\Type\BatchCastingInterface;
use DateTimeImmutable;
use DateTimeInterface;
use DateTimeZone;
use Exception;
Expand Down Expand Up @@ -141,6 +142,9 @@ public function toDatabase($value, Driver $driver)
if ($this->dbTimezone !== null
&& $this->dbTimezone->getName() !== $value->getTimezone()->getName()
) {
if (!$value instanceof DateTimeImmutable) {
$value = clone $value;
}
$value = $value->setTimezone($this->dbTimezone);
}

Expand Down
2 changes: 2 additions & 0 deletions tests/TestCase/Database/Type/DateTimeTypeTest.php
Expand Up @@ -146,9 +146,11 @@ public function testToDatabase()
$result = $this->type->toDatabase($date, $this->driver);
$this->assertEquals('2013-08-12 15:16:17', $result);

$tz = $date->getTimezone();
$this->type->setTimezone('Asia/Kolkata'); // UTC+5:30
$result = $this->type->toDatabase($date, $this->driver);
$this->assertEquals('2013-08-12 20:46:17', $result);
$this->assertEquals($tz, $date->getTimezone());

$this->type->setTimezone(new DateTimeZone('Asia/Kolkata'));
$result = $this->type->toDatabase($date, $this->driver);
Expand Down

0 comments on commit c5f27f3

Please sign in to comment.