【问题标题】:How to compare datetime in cakephp4如何比较 cakephp 4 中的日期时间
【发布时间】:2021-09-13 04:38:34
【问题描述】:

我正在使用以下代码来比较 DB DateTime 和输入字段 DateTime 是否相等但它不起作用,请帮我解决这个问题-

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

【问题讨论】:

  • 假设预约时间完全相等,$dt 将返回true。否则它将返回false

标签: php mysql datetime cakephp compare


【解决方案1】:

始终尝试对变量使用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'));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-20
    • 2010-12-25
    • 2014-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    相关资源
    最近更新 更多