Jesse
Jesse

Reputation: 25

PHP Range function for creating steps between 2 dates

I'm trying to create a range of dates between 2 dates, but the max amount of steps is 10. I tried using the range() function but that only works for alphabetical and numeric steps as far as I figured out.

So for example I have a date 03/07/2018 and a date 23/04/2015, I'd like to get 10 steps in between from the start till the end.

Simple example would be 01/01/2018 till 01/12/2018 you'd get start and end steps + the 10 steps added (01/02/2018, 01/03/2018) etc. And ofcourse if you have less then 10 steps (days) in between, create less steps.

What I have now is:

$begin = new DateTime( '2012-08-01' );
$end = new DateTime( '2012-08-31' ); 

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

foreach($daterange as $date){
    echo $date->format("Y/m/d") . "<br>";
}

But instead of having the P1D interval for DateInterval(), I want it to be 10 steps.

Please help me out, thanks!

Upvotes: 2

Views: 186

Answers (2)

Lovepreet Singh
Lovepreet Singh

Reputation: 4840

You should try following code to find 10 intervals between given dates:

$begin = new DateTime('2012-08-01');
$end = new DateTime('2012-08-31');

$x = $end->diff($begin);
$intervalDays = ceil($x->days / 10);
$interval = new DateInterval('P' . $intervalDays . 'D');
$daterange = new DatePeriod($begin, $interval, $end);

foreach ($daterange as $date) {
    echo $date->format("Y/m/d") . "<br>";
}

Your code is almost near to the solution and a little effort make it as you required.

Upvotes: 0

Mischa
Mischa

Reputation: 1601

Get the amout of days inbetween the start and end date like here. Then divide the amount by n. Then loop i=1 to n and add the result to the start-date every time you run through the loop (Datetime::modify). Cache the results in an array. Done.

Upvotes: 1

Related Questions