Ahmad Raza Ghausia Malang Ahmad Raza Ghausia Malang - 5 months ago 11
PHP Question

php current time and mysql tables time

I have a store site where I am using the opening and closing time of the store and it is working fine like if the opening time is 08:00 am and closing time is 09:00 pm.
But it is not working if the opening time is 11:30 am and closing time is 04:00 am.
My code is below:

<?php
date_default_timezone_set("Asia/Kuwait");
$rest_oc = mysql_query("SELECT * FROM timing WHERE sr_id = '".$rm_id."'");
while ($oc = mysql_fetch_array($rest_oc)) {
$timo = $oc['open'];
$timc = $oc['close'];
$ptime = date("h:i a");

$date1 = DateTime::createFromFormat('H:i a', $ptime);
$date2 = DateTime::createFromFormat('H:i a', $timo);
$date3 = DateTime::createFromFormat('H:i a', $timc);

if ($date3 < $date2) {
$date3->add(new DateInterval('P1D'));
}

if ($date1 >= $date2 && $date1 <= $date3) {
?>
<div class="tagR">
<img src="images/openN.png" alt=""/>
</div>
<?php }else{ ?>
<div class="tagR">
<img src="images/closed.png" alt=""/>
</div>
<?php } } ?>

Answer

Well that won't work because 4am is obviously before 11:30am if all you are using is time. Add this before your if condition

if ($date1 < $date2) {
    $date2->sub(new DateInterval('P1D'));
} else {
    if ($date3 < $date2) {
        $date3->add(new DateInterval('P1D'));
    }
}
Comments