John Davidson

Substract Time Logic - PHP

0 comments
Message:


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.



My Answer:
You can achieve this by adding some conditions inside the loop to check if the current time slot is in the past or not. Here's an updated version of your code that includes these conditions:

php
$start_time = "14:00:00";
$end_time = "22:30:00";
$current_time = strtotime(date("H:i:s"));

for ($i = strtotime($start_time); $i < strtotime($end_time); $i = $i + 1800) {
if ($i < $current_time) {
continue; // Skip past time slots
}

// Add an extra buffer time of 1 hour
if ($i < $current_time + 3600) {
continue; // Skip time slots within the next hour
}

echo '
  • ' . date("g:i A", $i) . '
  • ';
    }


    This code will only display time slots starting from the next hour after the current time and will skip past time slots.

    Rate this post

    3 of 5 based on 7238 votes

    Comments




    © 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
    Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us