简体   繁体   中英

Display a list of past 11 months from current date

I am drawing a bar graph and the values on the x-axis are the months in the last one year period. For example, this is March 2014; so the values on the x-axis range from April 2013 to March 2014 which is the current month.

I am using echo date('M'); to print the current month and echo date('M', strtotime(' -1 month')); and echo date('M', strtotime(' -2 month')); and so on to get all previous months.

These have been working fine until today, 29th March.

Where 'Feb' is supposed to be is also printing 'Mar'. I figure it is because February has 28 days.

Is there an easy fix to this without having to use if... else statements or if... else shorthand statements on all echo statements telling it to echo date('M', strtotime('-n month 2 days')); ?

This is due to how PHP handles date math. You need to make sure you are always working with the first of the month to ensure February does not get skipped.

DateTime() , DateInterval() , and DatePeriod() makes this really easy to do:

$start    = new DateTime('11 months ago');
// So you don't skip February if today is day the 29th, 30th, or 31st
$start->modify('first day of this month'); 
$end      = new DateTime();
$interval = new DateInterval('P1M');
$period   = new DatePeriod($start, $interval, $end);
foreach ($period as $dt) {
    echo $dt->format('F Y') . "<br>";
}

See it in action

You can obviously change $dt->format('F Y') to $dt->format('M') to suit your specific purposes. I displayed the month and year to demonstrate how this worked.

Thanks John Conde

This is how I used it:

$start    = new DateTime('11 months ago');
// So you don't skip February if today is day the 29th, 30th, or 31st
$start->modify('first day of this month'); 
$end = new DateTime();
//So it doesn't skip months with days less than 31 when coming off a 31-day month
$end->modify('last day of this month');
$interval = new DateInterval('P1M');
$period   = new DatePeriod($start, $interval, $end);
foreach ($period as $dt) 
    {
        $monthNames[] = $dt->format('M');
    }

This is because I needed to echo them inline within a <span> . The first value in the array is therefore used as:

<span><?php echo $monthNames[0]; ?></span> //As of March 2014, this prints Apr

Second value:

<span><?php echo $monthNames[1]; ?></span> //As of March 2014, this prints May

And so on.

Hope this helps someone who lands here looking for this same fix.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM