Splitting a start and end date by interval in PHP [duplicate]
-
26-10-2019 - |
Question
This question already has an answer here:
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.
Solution
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);
}
OTHER TIPS
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>";
}
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow