Search code examples
phpjsondatetimephp-8.1

How to compare two datetime form Json data with the current datetime in PHP 8


I want to compare two DateTime from JSON data with the current DateTime. compare the start date & end date with the current date to data between these two dates. If dates do not match give 0 answer.



$json = '[ 
  {
     "type":"playlist",
     "id": "35",
      "start_datetime": "2022-09-28 09:48",
      "end_datetime": "2022-09-28 09:51"
  },
  {
     "type":"asset",
     "id": "4",
      "start_datetime": "2022-09-29 07:00",
      "end_datetime": "2022-09-29 07:30"
  },
  {
     "type":"asset",
     "id": "4",
      "start_datetime": "2022-09-29 09:00",
      "end_datetime": "2022-09-29 09:30"
  }
]';

function find_events($events, $date) {
    $date = new DateTime($date);
    foreach ($events as $event) {
      $from = (new DateTime($event['start_datetime']));
      $to = (new DateTime($event['end_datetime']));
      if ($date >= $from || $date <= $to) {
           $r= "{$event['start_datetime']} to {$event['end_datetime']}".'<br>';
        }else{
          $r=0;
        }
    }
      return $r;
}

$events = json_decode($json, true);
print_r(find_events($events, '2022-09-29 07:00'));

?>```


Solution

  • Although the wording is not very clear, I am assuming you want to check if the date provided falls within the "from" and "to" dates. I also assume you want it to analyse all the dates in the array.

    Right now it will just return the result from the last item in the array - since you are overwriting the result with every loop. And also, your comparison logic is wrong:

    if ($date >= $from || $date <= $to)
    

    says "if the date is after the 'from' date OR before the 'to' date". But to check if it's between those dates, clearly both conditions will need to be true.

    To fix this, change the || to && in that line above, and also you can concatenate the results into a string, instead of overwriting them, so that you see every result.

    function find_events($events, $date) {
        $date = new DateTime($date);
        $r = "";
        
        foreach ($events as $event) {
          $from = (new DateTime($event['start_datetime']));
          $to = (new DateTime($event['end_datetime']));
        
          if ($date >= $from && $date <= $to) {
               $r.= "{$event['start_datetime']} to {$event['end_datetime']}".'<br>';
          }
          else{
              $r.= "0<br>";
          }
        }
         
        return $r;
    }
    

    Demo: https://3v4l.org/30eIo