1

Is there any function to split a start and end date into chuncks of $interval days (or months)? For example:

$interval = new DateInterval('P10D');
$start    = new DateTime('2012-01-10');
$end      = new DateTime('2012-02-16');

$chunks = splitOnInterval($start, $end, $interval);

// Now chunks should contain
//$chunks[0] = '2012-01-10'
//$chunks[1] = '2012-01-20'
//$chunks[2] = '2012-01-30'
//$chunks[3] = '2012-02-09'
//$chunks[3] = '2012-02-16'

I think DatePeriod can help, but i didn't find any way on how i can use it.

Charles
  • 50,010
  • 13
  • 100
  • 141
gremo
  • 48,580
  • 70
  • 242
  • 401

2 Answers2

6

Check this article on how to iterate over valid calender days.

In php its something like,

$start = strtotime('2012-01-10');
$end1 = strtotime('2012-02-16');
$interval   = 10*24*60*60; // 10 days equivalent seconds.
$chunks = array();
for($time=$start; $time<=$end1; $time+=$interval){
    $chunks[] = date('Y-m-d', $time);
}
Shiplu Mokaddim
  • 54,465
  • 14
  • 131
  • 183
  • if I have to devide 18 months (2017-01-01, 2018-30-06) into equal let say 5 number of months, then what changes I will need to make in the above code?. – Neeraj Mar 14 '18 at 07:19
2

Here is an example to iterate over days, over month is working accordingly with other interval

<?php

$begin = new DateTime( '2012-11-01' );
$end = new DateTime( '2012-11-11' );
$end = $end->modify( '+1 day' );

$interval = new DateInterval('P1D');
$daterange = new DatePeriod($begin, $interval ,$end);

foreach($daterange as $date){
echo $date->format("Y-m-d") . "<br>";
}
?>
Dukeatcoding
  • 1,336
  • 2
  • 19
  • 33