Igor O
Igor O

Reputation: 301

Trying to find gaps between dates in PHP

I'm trying to find gaps between dates, example:

$arrayTest = (
              array('from'=>'2017-07-10 15:22:45', 'to'=>'2017-07-11 16:22:46'),
              array('from'=>'2017-07-11 16:22:47', 'to'=>'2017-08-05 07:10:09'),
              array('from'=>'2017-08-05 07:10:10', 'to'=>'2017-09-22 09:25:12'),
              array('from'=>'2017-09-22 09:25:15', 'to'=>'2017-10-18 08:13:58'),
              array('from'=>'2017-10-18 08:13:58', 'to'=>'2017-11-29 13:29:12')
);

In this example, the line 4 from (2017-09-22 09:25:15) has 3 seconds more than line 3 to (2017-09-22 09:25:12). I guess the best way to do this is converting to timestamp strtotime(), but I'm a bit confused: how would be the best way to check that groups of From->To.. if somehow there's a gap in between?

Output: For this case, just return 1 (or the number of gaps), cause there's one gap. if all periods connect and is not missing any "space", returns 0.

Upvotes: 0

Views: 522

Answers (1)

Andreas
Andreas

Reputation: 23968

You need to loop and use strtotime.

$arr = array(
          array('from'=>'2017-07-10 15:22:45', 'to'=>'2017-07-11 16:22:46'),
          array('from'=>'2017-07-11 16:22:47', 'to'=>'2017-08-05 07:10:09'),
          array('from'=>'2017-08-05 07:10:10', 'to'=>'2017-09-22 09:25:12'),
          array('from'=>'2017-09-22 09:25:15', 'to'=>'2017-10-18 08:13:58'),
          array('from'=>'2017-10-18 08:13:58', 'to'=>'2017-11-29 13:29:12')
);
$gap = false;
For($i=0; $i<count($arr)-1; $i++){ //I count to -1 due to $i+1 in the calculation below
    $diff = strtotime ($arr[$i+1]['from']) - strtotime ($arr[$i]['to']);
    If($diff >1){ // if there is more than one second gap
        $gap = true;
        Echo "key " . $i . " to " . ($i+1) .". Missing " .$diff . " seconds";
    }
}

https://3v4l.org/pNviX

Upvotes: 4

Related Questions