我试图根据我的数据库中记录的时间显示不同的内容。
从晚上1800点到早上8点显示内容B. 其余剩余时间显示内容A.
我的数据库字段存储时间字段,所以在数据库1800 pm存储为18:00:00同样到0800:00,存储为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。
答案 0 :(得分:1)
if (date("H:i") >= '08:00' && date("H:i") <= '18:00') {
// Retrieve content 'A'
} else {
// Retrieve content 'B'
}
答案 1 :(得分: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';
}