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
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With