0

I would like to identify the missing dates in a PHP array

for example

this range

2013-06-12
2013-06-13
2013-06-26
2013-06-27
2013-06-29

has the following dates missing:

2013-06-14
2013-06-15
2013-06-16
...
2013-06-24
2013-06-25
2013-06-28

How can I identify the missing dates?

Franco
  • 2,846
  • 7
  • 35
  • 54
  • 1
    as a starting point take a look at http://stackoverflow.com/questions/3207749/i-have-2-dates-in-php-how-can-i-run-a-foreach-loop-to-go-through-all-of-those-d and http://stackoverflow.com/questions/5209057/loop-through-dates-with-php – Sean Jun 05 '13 at 05:12

1 Answers1

7

Here's a good way to get all missing dates in an array:

<?php
$myDates = array("2013-06-12", "2013-06-13", "2013-06-26", "2013-06-27", "2013-06-29");
$missingDates = array();

$dateStart = date_create("2013-06-01");
$dateEnd   = date_create("2013-06-".date("t", mktime(0, 0, 0, 6, 1, 2013)));
$interval  = new DateInterval('P1D');
$period    = new DatePeriod($dateStart, $interval, $dateEnd);
foreach($period as $day) {
  $formatted = $day->format("Y-m-d");
  if(!in_array($formatted, $myDates)) $missingDates[] = $formatted;
}

print_r($missingDates);
?>

This will result in:

Array
(
    [0] => 2013-06-01
    [1] => 2013-06-02
    [2] => 2013-06-03
    [3] => 2013-06-04
    [4] => 2013-06-05
    [5] => 2013-06-06
    [6] => 2013-06-07
    [7] => 2013-06-08
    [8] => 2013-06-09
    [9] => 2013-06-10
    [10] => 2013-06-11
    [11] => 2013-06-14
    [12] => 2013-06-15
    [13] => 2013-06-16
    [14] => 2013-06-17
    [15] => 2013-06-18
    [16] => 2013-06-19
    [17] => 2013-06-20
    [18] => 2013-06-21
    [19] => 2013-06-22
    [20] => 2013-06-23
    [21] => 2013-06-24
    [22] => 2013-06-25
    [23] => 2013-06-28
    [24] => 2013-06-30
)
Rob W
  • 9,134
  • 1
  • 30
  • 50
  • Note that the last 3 arguments for `mktime()` are month, day, year (not day, month, year). – Arjan Jun 05 '13 at 05:27
  • @Arjan: good catch, forgot to change that when I had initially tested January dates and wondered why they weren't removing his dates.. then noticed it was June! Answer has been updated :) – Rob W Jun 05 '13 at 15:05
  • If DateInterval or DatePeriod classes are not found for you, add a backslash before them ie `\DateInterval` - you're likely using them inside of a namespaced class – Grant Aug 02 '22 at 13:00