如何解决如何在CakePHP中将DatetTime与时区保持一致
我有一个使用UTC时区的MySQL,并尝试将CakePHP实体保存到数据库中的datettime列。
当PHP DatetTime对象具有时区(与UTC不同)时,CakePHP不会在保存期间将值转换为UTC。
我写了一个简短的测试来演示这个问题。
public function testTryCreateReservation(): void
{
$e = $this->Reservations->newEmptyEntity();
$now = new \DateTime();
$start = new \DateTime('now',new \DateTimeZone('Europe/Vienna'));
$start->setTimestamp($now->getTimestamp());
$end = new \DateTime('now');
$end->setTimestamp($now->getTimestamp());
$e->start_time = $start;
$a = $this->Reservations->get($a->id);
$this->assertEquals($end,$a->end_time);
$this->assertEquals($start,$a->start_time); // this fails
}
这是phpunit输出
Failed asserting that two DateTime objects are equal.
--- Expected
+++ Actual
@@ @@
-2020-09-02T07:54:45.000000+0200
+2020-09-02T07:54:45.000000+0000
CakePHP不能转换值吗?
解决方法
启用时区转换
当列为datetime
类型时,ORM将转换时区,然后在相应的数据库类型实例(\Cake\Database\Type\DateTimeType
)上配置数据库时区。
您可以在bootstrap.php
中执行此操作,底部有一个部分显示了如何构建和配置数据库类型:
\Cake\Database\TypeFactory::build('datetime')->setDatabaseTimezone('UTC');
还应注意,这还将启用相反的转换,即从数据库时区到应用程序的默认时区(App.defaultTimezone
)!如果您不想这样做,可以通过setKeepDatabaseTimezone()
方法将其禁用:
\Cake\Database\TypeFactory::build('datetime')->setKeepDatabaseTimezone(true);
然后将使用为数据库类型配置的时区(将 not 转换为)创建对象。
我想,如果菜谱中某处有专门的数据库时区转换部分,那不会有什么害处。
仅将时区转换应用于特定列
请注意,如果您不希望将其全局应用,也可以映射一个新类型并将其分配给特定的表列:
// in your bootstrap.php
\Cake\Database\TypeFactory::map('customDateTime',\Cake\Database\Type\DateTimeType::class);
\Cake\Database\TypeFactory::build('customDateTime')->setDatabaseTimezone('UTC');
// in the table class where you want this type to apply to a specific column
protected function _initializeSchema(\Cake\Database\Schema\TableSchemaInterface $schema): \Cake\Database\Schema\TableSchemaInterface
{
$schema->setColumnType('column_name','customDateTime');
return $schema;
}
另请参见
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。