【问题标题】:PHP function to compare now time to time in databasePHP函数在数据库中不时比较
【发布时间】:2014-12-15 17:46:45
【问题描述】:

我正在尝试根据我的数据库中记录的时间显示不同的内容。

从 1800 pm 到 0800 am 显示内容 B。 剩余时间显示内容A。

我的数据库字段是存储时间字段,因此在数据库中 1800 pm 存储为 18:00:00 与 0800 am 相同,它存储为 08:00:00。

以下是我在 18:00:00 到 08:00:00 之间获取内容 B 的逻辑:

$now = strtotime(date('H:i:s'));
$time_from = strtotime($data['date_from']); //18:00:00
$time_to = strtotime($data['date_to']); // 08:00:00
if($now >= $time_from && $now <= $time_to){
   echo 'content A';
}

上面的代码只有在我的$time_to 在 23:59:59 之内时才有效,因为$now 总是大于08:00:00。假设现在是23:30:00,我的代码永远不会回显“内容A”,因为23:30:00 大于08:00:00

我怎样才能使逻辑工作按时间检查才显示内容?

@All,我再次编辑代码。是的。我确实放了 $now = strtotime(date('H:i:s'));。但它也不能正常工作。首先,当前现在的 unix 时间戳将始终大于 08:00:00 unix 时间戳。假设现在的时间是 23:30:00。 unix 时间戳总是大于 08:00:00。

【问题讨论】:

标签: php mysql time


【解决方案1】:

在进行比较之前,您还需要strtotime() 您的$now 变量,尝试:

$now = date('H:i:s');
$time_from = strtotime($data['date_from']); //18:00:00
$time_to = strtotime($data['date_to']); // 08:00:00
$now_str = strtotime($now);
if($now_str >= $time_from && $now_str <= $time_to){
   echo 'content A';
}

【讨论】:

  • 我确实将 strtotime 添加到我的 $now 中。我在我的问题中错过了那部分。因此我编辑了它。即使使用strtotime,也无助于解决问题。假设现在的时间是 23:30:00。 unix 时间戳总是大于 08:00:00。
【解决方案2】:
if (date("H:i") >= '08:00' && date("H:i") <= '18:00') {
    // Retrieve content 'A'
} else {
    // Retrieve content 'B'
}

【讨论】:

  • 08:00:00 应该是
  • 这种方式会起作用@Kimberlee - 这与您尝试它的方式不同。确定何时显示内容 A,其他时间显示内容 B。
  • 是的。有用。我认为反向逻辑不适用于我的情况。我已经对我的代码和逻辑进行了更改。谢谢丹穆伦!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-02-14
  • 1970-01-01
  • 1970-01-01
  • 2016-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多