如何在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不能转换值吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)