Reputation: 35
Let's just say, for the sake of simplicity, I have two arrays, in the first is a time range in which I am wanting to go to sleep. I must sleep for the entire two hour period without any interruption, so the bed must be available during that time. The function needs to check if the bed will be available when I want to sleep.
$aSleeping = array(
'start' => '6:00 AM',
'end' => '10:00 AM'
);
$aBedAvail = array(
'start' => '10:00 AM',
'end' => '12:00 PM'
);
I have tried this, it worked on one time range, but not another, any help to improve on this is greatly appreciated.
function checkRange($aSleeping,$aBedAvail){
if(
strtotime($aSleeping['start']) >= strtotime($aBedAvail['start']) &&
strtotime($aSleeping['end']) <= strtotime($aBedAvail['end'])
){
return true;
}else{
return false;
}
}
Upvotes: 0
Views: 239
Reputation: 41820
Your function looks like it would work just fine unless either of the ranges has an end time earlier than the start time (an evening to morning range). You can correct that by checking for that condition and moving the end time to the next day if it is before the start time.
function checkRange(array $outer, array $inner) {
// create DateTimes
$outer = array_map('date_create', $outer);
$inner = array_map('date_create', $inner);
// Correct earlier end times
$outer['start'] > $outer['end'] && $outer['end']->modify('+24 hours');
$inner['start'] > $inner['end'] && $inner['end']->modify('+24 hours');
// compare ranges and return result
return $outer['start'] >= $inner['start'] && $outer['end'] <= $inner['end'];
}
Upvotes: 0
Reputation: 1634
Because a user can start sleeping at 11h59pm in one day and ends in next day, you must consider using the day information in comparison. PHP DateTime helps enable other date capabilities, in case you need perform other actions with date vars:
$aSleeping = array(
'start' => new DateTime('2020-03-10 05:00:00'),
'end' => new DateTime('2020-03-10 12:00:00')
);
$aBedAvail = array(
'start' => new DateTime('2020-03-10 05:00:00'),
'end' => new DateTime('2020-03-10 12:00:00')
);
function checkRange($aSleeping,$aBedAvail){
return ($aSleeping['start'] >= $aBedAvail['start'] && $aSleeping['end'] <= $aBedAvail['end']) ? true : false;
}
var_dump(checkRange($aSleeping,$aBedAvail));
Upvotes: 1