2014-10-20 33 views
1

我试图根据记录在我的数据库中的时间显示不同的内容。PHP函数现在比较数据库中的时间

从1800点到0800点显示内容B. 剩余时间显示内容A.其余

我的数据库字段存储时间字段,以便在数据库1800点被存储为18:00:00相同到上午8点,它被存储为08:00:00。

下面是我的逻辑来获取内容B时的时间是18:00:00 08:00:00之间:

$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 as $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

为什么你不使用碳库处理日期是很容易的https:// github上.com/briannesbitt/Carbon – Fabrizio 2014-10-20 16:55:06

回答

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

08:00:00应该<=因为我期待在18:00:00至08:00:00之间显示内容。逻辑应该倒退。它应该是从18:00:00到08:00:00 – 2014-10-20 17:50:22

+0

这种方式将工作@Kimberlee - 这是你如何尝试它的不同逻辑。计划何时显示内容A,并在其他时间显示内容B. – danmullen 2014-10-20 19:52:52

+0

是的。有用。我不认为这种反向逻辑对我来说是行得通的。我修改了我的代码和逻辑。谢谢Danmullen! – 2014-10-21 03:43:17

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'; 
} 
+0

我确实在我的$现在添加了strtotime。我错过了我的问题中的那一部分。因此我编辑了它。即使采用时间,也无助于解决问题。假设现在的时间是23:30:00。 unix时间戳将始终大于08:00:00。 – 2014-10-20 17:48:14