I want to implement this logic in PHP CodeIgniter.
I have a check-in time options that are in intervals of 30 minutes from 00:00 to 23:30. e.g the time can be 00:00 ,00:30, 01:00, 01:30, 02:00, 02:30 ,03:00, 03:30 ..... 23:30.
Because of 2-hour booking window, the system will display a limited number of check-in time options and as such, a customer cannot see all our check-in time options. It will work based on the current time of the system. The customer will see check-in time options from the nearest check-in time option from his current time till the next 2 hours. For example, the current time is 00:50. The nearest check-in time option is 01:00 and 2 hours from 01:00 is 03:00. Hence, the customer will only see the following check-in time options which will be 5 options at any time of the day; 01:00, 01:30 ,02:00,02:30,03:00 etc
I can't seem to be able to translate this to PHP.
So you need to essentially parse the current time in to hours and minutes, then using a DateInterval
go to the nearest (next/forward) half-hour or hour. This becomes option 1. From there it is a matter of generating the next 4 options to equal 2 hours from the first available option. We do this with a for
loop and adding on 30m
each iteration until all the options are complete.
<?php
function check_in_options($time) {
$dt = new DateTime($time);
$minutes = $dt->format('i');
$hour = $dt->format('H');
$interval = $minutes >= 30 ? 60 - $minutes : 30 - $minutes;
$dt->add(new DateInterval("PT{$interval}M"));
$options[] = $dt->format('H:i');
for ($x = 1; $x <= 4; $x++) {
$options[] = $dt->add(new DateInterval("PT30M"))->format('H:i');
}
return $options;
}
$time = '00:50';
$options = check_in_options($time);
echo '<pre>';
print_r($options);
Result:
Array
(
[0] => 01:00
[1] => 01:30
[2] => 02:00
[3] => 02:30
[4] => 03:00
)