Rahgav Rahgav - 2 months ago 6
PHP Question

Comparing current time with end time given by user in PHP

I am comparing current time with given time.but i am getting wrong results.

<?php
date_default_timezone_set('Asia/Kolkata');
//echo date("h:i a");
//echo $query2['endtime'];
if(date("h:i a") > $query2['endtime'])
{
$date = new DateTime(date("Y-m-d"));
$date->modify('+1 day');
echo $date->format('Y-m-d');
echo '<input type="date" name="date" id="date" min="'.$date->format('Y-m-d').'">';
}
else
{
echo '<input type="date" name="date" id="date" min="'.date("Y-m-d").'">';
}

?>


I have endtime using $query2['endtime'] from the database and I have cheched using echo.My end time is 5:00 pm.But I am getting wrong results .Please Help.

Answer

Since date() function will give you date string , you cannot check '>' operation on that. First you need to convert date string into timestamp using strtotime() then compare. Below code may help you

<?php 
date_default_timezone_set('Asia/Kolkata');
echo date("h:i a");
$query2= '05:00 pm';
$query21 =strtotime($query2);
echo $query21;
if(strtotime(date("h:i a")) > $query21)
{
    echo "yes";
}
else
{
    echo "no";
}
?>