简体   繁体   English

PHP函数现在可以不时比较数据库中的内容

[英]PHP function to compare now time to time in database

I am trying to show different content based on the time recorded in my database. 我试图根据数据库中记录的时间显示不同的内容。

From 1800 pm to 0800 am show content B. The rest of the remaining time show content A. 从1800 pm到0800 am显示内容B。其余时间显示内容A。

My database field is storing time field so in database 1800 pm is stored as 18:00:00 same goes to 0800 am, it is stored as 08:00:00. 我的数据库字段是存储时间字段,因此在数据库1800 pm中存储为18:00:00,直到0800 am,它存储为08:00:00。

Below is my logic to get content B when time is between 18:00:00 to 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';
}

The above code will only work if my $time_to is within 23:59:59 as $now will always be bigger than 08:00:00 . 上面的代码仅在$time_to在23:59:59内有效,因为$now始终大于08:00:00 Lets say the time now is 23:30:00 , my codes will never echo "content A" out because 23:30:00 is bigger than 08:00:00 . 可以说现在的时间是23:30:00 ,我的代码将永远不会回显“ content A”,因为23:30:00大于08:00:00

How can i make the logic work to check by time only then to display the content? 我如何才能使逻辑工作仅按时间检查然后显示内容?

@All, im editing the code again. @All,即时通讯再次编辑代码。 Yes. 是。 i did put $now = strtotime(date('H:i:s'));. 我确实把$ now = strtotime(date('H:i:s'));. But it is not working as well. 但是它不能很好地工作。 Firstly, the current now unix timestamp will always be bigger than 08:00:00 unix timestamp. 首先,当前的unix时间戳将始终大于08:00:00 unix时间戳。 let's say the time now is 23:30:00. 假设现在的时间是23:30:00。 The unix timestamp will always be bigger than 08:00:00. Unix时间戳将始终大于08:00:00。

if (date("H:i") >= '08:00' && date("H:i") <= '18:00') {
    // Retrieve content 'A'
} else {
    // Retrieve content 'B'
}

before making the comparision, you need to strtotime() your $now variable as well, try: 在进行比较之前,您还需要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';
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM