Search code examples
phparraysdatedynamic-arraysdate-range

Getting date range grouped by month


I have an form where users can select a date range. For example, a date range could be:

$start = "5/1/2013";
$end = "6/5/2013";

I can easily grab the day difference between the two by doing something like:

$date1 = new DateTime($start);
$date2 = new DateTime($end);

$interval = $date1->diff($date2)

But if I want to build an array that would contain a monthly grouping, where each array would have the minimum and maximum date for each group. For example:

array(2) {
  [0]=>
  array(2) {
    [0]=>
    string(8) "5/1/2013"
    [1]=>
    string(9) "5/30/2013"
  }
  [1]=>
  array(2) {
    [0]=>
    string(8) "6/1/2013"
    [1]=>
    string(8) "6/5/2013"
  }
}

How could I accomplish this?


Solution

  • Use $dateX->getTimestamp(), than iterate between these two timestamps by an interval of 60*60*24*30 (one month) and use date("d/m/Y", $time) to get the formatted date.