Skip to content
Advertisement

Substract Time Logic – PHP

I want to show time slots between 2 times. Start time & End time. Used below code, it’s working fine. It loops start and end time and add 30 mins to time. Starts from 2:00pm, 2:30pm, 3:00pm all the way till 10:00pm

$start_time =  "14:00:00";
$end_time =  "22:30:00";

@for ($i = strtotime($start_time); $i < strtotime($end_time); $i=$i+1800)
  <li data-time="{{date('g:i A', $i)}}" class="timefield">{{date("g:i A", $i)}}</li>
@endfor

What I am stuck on is 2 parts

  • Hide past time, lets say right now is 4:00pm, it should hide past time slots i-e 2:00pm,2:30pm,:3:00pm,3:30pm
  • If right now is 4:00pm, it should start from 5:00pm all the way till 10:00pm. Adding extra buffer time of 1 hour.

Advertisement

Answer

You could insert the current timestamp in your logic like this:

$start_time =  strtotime("14:00:00");
$end_time =  strtotime("22:30:00");
    
$now = (new DateTime())->getTimestamp();
$nowRemaining = $now % 1800; // Divide to half hours & get the remaining seconds
$nowRounded = $now - $nowRemaining; // Round to half hours
$nextHour = $nowRounded + ($nowRemaining == 0 ? 3600 : 5400); // Add the extra buffer
    
for ($i = max($start_time, $nextHour); $i < $end_time; $i=$i+1800) {
  ...
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement