I want to detect how to detect if the day is in the specific settings that I save.
I already save the settings
$checkday = "Sunday";
$period = "48"; // this in hours
So I need to check if today in this week is Sunday 48 hours after (means Tuesday) then run a function.
I already make these code
$starttimer = date('Y-m-d 00:00:00', strtotime($checkday));
$endtimer = date('Y-m-d H:i:s', strtotime(' ' . $period . ' hour', strtotime(date('Y-m-d 00:00:00'))));
if(time() >= strtotime($starttimer) && time() <= strtotime($endtimer)){
// this should run a function
}
This code is working if today is Sunday, but the problem is when today is Monday it will detect next Week Monday. I need it to check from this week Sunday 48 hours after then run function.
The conclusion is I want to run the function on every week start from Sunday 48 hours after.
Thanks for reading my problem, hope someone can help me.
CodePudding user response:
I think you need get day of this week.
because if checkday = "Monday" then $starttimer will return Monday of next week.
<?php
$checkday = 'Monday';
$period = 48;
$day_this_week = "$checkday this week";
$starttimer = date('Y-m-d 00:00:00', strtotime($day_this_week));
$endtimer = date('Y-m-d H:i:s', strtotime(' ' . $period . ' hour', strtotime(date('Y-m-d 00:00:00'))));
var_dump($starttimer);//string(19) "2022-09-12 00:00:00"
CodePudding user response:
You can use the flexibility of strtotime
to find the time of the last occurance of $checkDay
. You also need to check to see that today is the check day and run in that condition as well.
<?php
$checkDay = 'Sunday';
$period = 48;
$isCheckDay = date('w', strtotime($checkDay)) === date('w');
$start = strtotime('last ' . $checkDay);
$end = strtotime(date('Y-m-d', $start) . ' ' . $period . ' hours');
$now = time();
if ($isCheckDay || ($now >= $start && $now <= $end)) {
echo 'run function';
}