skip to Main Content

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


  1. using the DateTime builtin class makes life quite easy here

    $power_date = '12/16/2022 02:40:40 PM';
    $power_d = (new DateTime())->createFromFormat('m/d/Y H:i:s a', $power_date);
    
    echo 'power_date =            ' . $power_d->format('d/m/Y H:i:s');
    echo PHP_EOL;
    
    $valid_end = new DateTime('today 07:00:00');
    echo 'Valid End Date time =   ' . $valid_end->format('d/m/Y H:i:s');
    echo PHP_EOL;
    
    $valid_start = new DateTime('yesterday 07:00:00');
    echo 'Valid Start Date time = ' . $valid_start->format('d/m/Y H:i:s');
    echo PHP_EOL;
    
    if ( $power_d > $valid_start && $power_d < $valid_end) {
        echo 'VALID';
    } else {
        echo 'INVALID';
    }
    
    Login or Signup to reply.
  2. The trick is to determine the correct cutoff time or correct date for the cutoff. This is much easier with the DateTime object.

    $last_power = 'yesterday 7:00:01';
    $current = new DateTime('today 6:59:59');  // demo, for production use: new DateTime('now') 
    $new_day = new DateTime('today 7:00');  // can be past or future
    $date_power = new DateTime($last_power); // you may need to use: (new DateTime())->createFromFormat()
    
    if($current < $new_day){ // prior to 7am
        $new_day->modify('-1day'); // adjust the cutoff date
    }
    // now a simple comparison
    if($date_power < $new_day){
        echo "true, price is older than " .$new_day->format('Y-m-d, H:i:s');
    }else{
        echo "false, price is same age or newer than " .$new_day->format('Y-m-d, H:i:s');
    }
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search