Question

Is there a way in PHP to get the current and the previous 5 months in the following format?

April 2014
March 2014
February 2014
January 2014
December 2013
November 2013
Was it helpful?

Solution

Have you tried following:

<?php
echo date('F, Y');
for ($i = 1; $i < 6; $i++) {
  echo date(', F Y', strtotime("-$i month"));
}

Let me know, if this wont work.

OTHER TIPS

Do not use:

<?php
for ($i = 0; $i <= 6; $i++) {
  echo date('F Y', strtotime(-$i . 'month'));
}
// With date e.g.: "May, 31", outputs:
// May, 2018, May 2018, March 2018, March 2018, January 2018, December 2017

You can fix it by:

<?php
for ($i = 0; $i <= 6; $i++) {
  echo date('F Y', strtotime('last day of ' . -$i . 'month'));
}

Or better use DateTime, e.g.:

$dateTime = new DateTime('first day of this month');
for ($i = 1; $i <= 6; $i++) {
    echo $dateTime->format('F Y');
    $dateTime->modify('-1 month');
}

Try this

for ($j = 0; $j <= 5; $j++) {
    echo date("F Y", strtotime(" -$j month"));
}

Why not use DateTime Object as

$start = new DateTime('first day of this month - 6 months');
$end   = new DateTime('last month');
$interval  = new DateInterval('P1M'); // http://www.php.net/manual/en/class.dateinterval.php

$date_period = new DatePeriod($start, $interval, $end);
$months = array();
foreach($date_period as $dates) {
  array_push($months, $dates->format('F').' '.$dates->format('Y'));
}

print_r($months);

Use strtotime and date

for( $i = 0; $i <= 5 ; $i++) {
     print date("F Y", strtotime("-".$i." month"))."\n";
}

to achieve another formats for date look PHP date format HERE

<?php
for ($i =0; $i < 6; $i++) {
    $months[] = date("F Y", strtotime( date( 'Y-m-01' )." -$i months"));
}

print_r($months)
?>

Try This..

for ($i = 1; $i <= 6; $i++) {
   $months[] = date("M-y", strtotime( date( 'Y-m-01' )." -$i months"));
}
print_r($months);
@php
   for($i=0; $i<=5; $i++) {
     $last_six_months[] =date("Y-m-d", strtotime( date( 'Y-m-01' )." -$i months"));
   }
    $last_six_months = array_reverse($last_six_months); // If you want to reverse...
@endphp

next >>>

 @foreach($last_six_months as $key => $row)
     <span>{{date('F Y',strtotime($row))}}</span>
 @endforeach
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top