如何在cakephp4中比较日期时间

qyuhtwio  于 2022-11-11  发布在  PHP
关注(0)|答案(1)|浏览(117)

我正在使用以下代码来比较数据库日期时间和输入字段日期时间是否相等,但它不工作,请帮助我从这个问题-

$appointment_time = $this->Appointments->find()->select(['appointment_time']);
$appointment_time1 = $this->request->getData('appointment_time');
$dt = ($appointment_time == $appointment_time1);
wkyowqbh

wkyowqbh1#

请始终尝试使用debug()函数作为变量,以了解两者之间的区别。

debug($appointment_time1);
debug($appointments);

在你的例子中,$appointment_time不是你所期望的,而是\Cake\ORM\Query对象,而$appointment_time1是一个字符串。

试试看:

// convert posted string to date time format
$appointment_time1 = date('Y-m-d H:i:s', strtotime($this->getRequest()->getData('datetime')));

// fetch data from db
$appointments = $this->Appointments->find()->select(['appointment_time']);

foreach ($appointments as $appointment) {
   echo $appointment->appointment_time->format('Y-m-d H:i:s') == $appointment_time1 ? 'OK' : 'NOT OK';
}

$appointment = $this->Appointments->find()->select(['appointment_time'])->first();

echo $appointment->appointment_time->format('Y-m-d H:i:s') == $appointment_time1 ? 'OK' : 'NOT OK';

还可以尝试:

$appointment->appointment_time->getTimestamp() == strtotime($this->getRequest()->getData('datetime'));

相关问题