Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: get last 6 months in format month year

Tags:

date

php

format

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
like image 433
user2571510 Avatar asked Apr 01 '14 11:04

user2571510


4 Answers

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.

like image 165
Tyralcori Avatar answered Nov 02 '22 06:11

Tyralcori


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');
}
like image 24
hellovoid Avatar answered Nov 02 '22 05:11

hellovoid


Try this

for ($j = 0; $j <= 5; $j++) {
    echo date("F Y", strtotime(" -$j month"));
}
like image 25
Sadikhasan Avatar answered Nov 02 '22 07:11

Sadikhasan


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);
like image 24
Abhik Chakraborty Avatar answered Nov 02 '22 07:11

Abhik Chakraborty