Find Closest Time Slots

Find Closest Timeslots

If you working on a booking application or web site, you might need to get closest time slots based on a given time. Let’s take a small example.

Customer says he prefers to come to the salon at 10.30am tomorrow.

Now you get a list of available time slots for tomorrow from database. To filter based on customer’s desired time, you can do this in database level or change the result set from database. Below piece of code shows how to achieve this with PHP.

$preferred_unix_time = strtotime($preferred_time);
$closest_blocks = [];
$closest_before = timeBefore($preferred_unix_time, $time_blocks);
if ($closest_before) {
  $closest_blocks[] = $closest_before;
}

$closest_after = timeAfter($preferred_unix_time, $time_blocks);
if ($closest_after) {
  $closest_blocks[] = $closest_after;
}

We have used strtotime() PHP function to convert time to Unix based time stamps considering accuracy.

function timeBefore($time, $time_blocks) {
    $closest_before = NULL;
    foreach ($time_blocks as $t) {
        if ($t['start_unix'] <= $time) {
            if (!$closest_before) {
                $closest_before = $t;
            } else {
                if ($t['start_unix'] > $closest_before['start_unix']) {
                    $closest_before = $t;
                }
            }
        }
    }

    return $closest_before;
}

function timeAfter($time, $time_blocks) {
    $closest_after = NULL;
    foreach ($time_blocks as $t) {
        if ($t['start_unix'] > $time) {
            if (!$closest_after) {
                $closest_after = $t;
            } else {
                if ($t['start_unix'] < $closest_after['start_unix']) {
                    $closest_after = $t;
                }
            }
            
        }
    }

    return $closest_after;
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *