Home > Software engineering >  3 Months date Interval Looping
3 Months date Interval Looping

Time:01-19

I want to loop month in 3 months interval, see code below:

for($i=1; $i<=3; $i  ){
$date=date('d-m-Y',strtotime("$i*3 month"));
echo "$date"."<br>";
}

but am getting the below Result:

01-01-1970
01-01-1970
01-01-1970

I want to achieve below Result:

19-03-2022
19-06-2022
19-09-2022

CodePudding user response:

function generateDates(string $startDate, int $count): array {
 $date = new DateTime($startDate);
 $dates = [ $date->format('d-m-Y') ];
  for ($i = 0; $i < $count - 1; $i  ) {
    $dateTime = $date->add(new DateInterval('P3M'));
    $dates[] = $dateTime->format('d-m-Y');
  }
  return $dates;
}

$result = generateDates('2022-03-19', 8);

print_r($result);   // This will print:

// Array
// (
//     [0] => 19-03-2022
//     [1] => 19-06-2022
//     [2] => 19-09-2022
//     [3] => 19-12-2022
//     [4] => 19-03-2023
//     [5] => 19-06-2023
//     [6] => 19-09-2023
//     [7] => 19-12-2023
// )

CodePudding user response:

Your main issue is that "$i*3 month" won't do the calculation *3 so this will evaluate to "1*3 month" which is not understandable by strtotime. In order to fix this you have to do the calculation then the concatenation (instead of a direct interpolation) such as:

for($i = 1; $i <= 3; $i  ){
    $date=date('d-m-Y',strtotime($i * 3 . " month"));
    echo "$date"."<br>";
}

You could enhace this, in fact strtotime has a second parameter that allows you to specify a base timestamp:

for($i = 0; $i < 3; $i  ){
    $date=date('d-m-Y',strtotime($i * 3 . " month", strtotime('2022-03-19')));
    echo "$date"."<br>";
}

strtotime may not be the best choice for this. I guess what you ultimately want to use is a combination of DateTime, DateInterval and, maybe, DatePeriod

  •  Tags:  
  • Related