I have a php code as shown below in which I want to display anything in between two calendar days of the week.
The values coming inside $data->{\"select_s
Here is my stab at it, using a mapping table and string concatenation. It doesn't work if the days are in reversed order. e.g. If today is Sunday and the value of select_start_day
is Fri
and the value of select_end_day
is Mon
, then it won't work.
'wed',
'start_time' => 143400,
'select_end_day' => 'wed',
'end_time' => 220000
];
$map_daysToNumbers = ['sun'=>1, 'mon'=>2, 'tue'=>3, 'wed'=>4, 'thu'=>5, 'fri'=>6, 'sat'=>7];
$startString = $map_daysToNumbers[$arr->select_start_day] . str_pad($arr->start_time, 6, '0', STR_PAD_LEFT);
$endString = $map_daysToNumbers[$arr->select_end_day] . str_pad($arr->end_time, 6, '0', STR_PAD_LEFT);
$tz = new \DateTimeZone('America/Toronto');
$today = new \DateTime('now', $tz);
$todayString = ($today->format('w')+1) . $today->format('His');
if($startString <= $todayString && $todayString <= $endString){
echo 'In range';
}
or date-based solution. Neither of them is guaranteed to fulfil your needs.
$arr = (object) [
'select_start_day' => 'tue',
'start_time' => 143400,
'select_end_day' => 'wed',
'end_time' => 220000
];
$tz = new \DateTimeZone('America/Toronto');
// extrapolate the start date looking 7 days back
$sDate = new \DateTime('tomorrow midnight', $tz);
$sDate->modify('last '.$arr->select_start_day);
$sDate->setTime(...str_split(str_pad($arr->start_time, 6, '0', STR_PAD_LEFT), 2));
// or bound the start date to be between last sunday and next saturday
$sDate = new \DateTime('Saturday last week', $tz);
$sDate->modify('next '.$arr->select_start_day);
$sDate->setTime(...str_split(str_pad($arr->start_time, 6, '0', STR_PAD_LEFT), 2));
// extrapolate the end date
$eDate = clone $sDate;
$eDate->modify('yesterday'); // workaround to consider the same day possibility
$eDate->modify('next '.$arr->select_end_day);
$eDate->setTime(...str_split(str_pad($arr->end_time, 6, '0', STR_PAD_LEFT), 2));
// Test against today
$today = new \DateTime('now', $tz);
var_dump($sDate);
var_dump($eDate);
var_dump($today);
if($sDate <= $today && $today <= $eDate){
echo 'In range';
}
The first way will always start in the past and depending on your range it might include today or not. The second will always be bound to the current week, which I believe is what you wanted.
As @mickmackusa and I said in the comments, the requirements given to you are vague and imprecise. You either need more rigid rules or a date based solution, i.e. you are given two precise dates (timestamps) and then you compare if a date falls between them. This is what I tried to do in my second option, but It is unknown if the date should be in the past or future.