Question

 $end = strtotime('2011-09-01');
 $start = strtotime('today');

 while($start > $end)
 {
echo date('F Y', $start) . "<br>";

$start = strtotime("-1 month", $start);
 }

Results: April 2014 March 2014 March 2014 February 2014 January 2014 December 2013 ...etc

Why am I getting March 2014 twice? Please if anybody could help, thanks.

Was it helpful?

Solution

I was able to get it working with DateTime(). By starting with the end date I was starting with the first of the month. That made the number of days in each month irrelevant. Then all I had to do was reverse the array of dates to have it meet your desired format.

$start    = new DateTime('2011-09-01');
$end      = new DateTime();
$interval = new DateInterval('P1M');
$period   = new DatePeriod($start, $interval, $end);

$months= array();
foreach ($period as $dt) { 
    $months[] = $dt->format('F Y');
}
$months = array_reverse($months);
echo implode('<br>', $months);

Demo

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top