-2

month adding problem

<?php 

$showMonthsQty = 3;
for($i = (1-$showMonthsQty); $i <= 0; $i++) 
{
    echo $date = date("Y-m-1", strtotime(" +$i months"));

}
?>

when it run's im not geting the desired answer.

OUTPUT

2018-03-1 
2018-05-1  <----------error
2018-05-1

but i needed output is :

2018-03-1    
2018-04-1 
2018-05-1

how can i get this ?pls help!... tnx in advance...:)

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
sreechith srk
  • 146
  • 12

1 Answers1

3

You can use DateTime and DateInterval.

$showMonthsQty = 3;
for($i = $showMonthsQty-1; $i >= 0; $i--) 
{
    $date = new \DateTime(date("Y-m-1")); // First day of the current month
    $date->sub(new \DateInterval(sprintf('P%sM', $i))); // Substract $i month (P%dM)

    echo $date->format('Y-m-d')."<br />";
}

Output:

2018-03-01
2018-04-01
2018-05-01

Is it what you're looking for ?

G1.3
  • 1,693
  • 8
  • 24