I need to compare a datetime field called "last_power" to a specific range time that starts at 7AM every day.
For example:
Day starts at 7AM.
NOW() = 2022/12/15 02:40:40 PM || last_power is setting to 2022/12/14 06:40:40 PM -> true
NOW() = 2022/12/15 02:40:40 PM || last_power is setting to 2022/12/15 11:40:40 AM -> false
I’m stucked when "last_power" is between midnight and 6:59 AM.
NOW() = 2022/12/15 12:40:40 AM || last_power is setting to 2022/12/14 01:40:40 AM -> SHOULD BE true because in my code "2022/12/15 12:40:40 AM" is < 7AM of today, but the result give me a false result.
//set
$current = time();
$new_day = strtotime('today 7:00');
$date_power = strtotime($last_power);
if ($current - $date_power >= (24 * 60 * 60) ||
($date_power < $new_day && $current >= $new_day))
{
echo "true";
//last_result < today 7:00AM -> you award your price
} else {
echo "false";
//last_result > today 7:00AM -> you have already received the price for today
}
2
Answers
using the DateTime builtin class makes life quite easy here
The trick is to determine the correct cutoff time or correct date for the cutoff. This is much easier with the
DateTime
object.The above will output the following (today being
2022-12-16
):false, price is newer than 2022-12-15, 07:00:00
Run it live here.