显示当前日期过去11个月的列表

时间:2014-03-29 18:27:45

标签: php date strtotime date-math

我正在绘制条形图,x轴上的值是过去一年中的月份。例如,这是2014年3月;所以x轴上的值范围从2013年4月到2014年3月,也就是当月。

我正在使用echo date('M');打印当前月份echo date('M', strtotime(' -1 month'));echo date('M', strtotime(' -2 month'));等等以获取前几个月。

直到今天,3月29日,这些工作一直很好。

'2月'应该也是'Mar'。我认为这是因为二月有28天。

是否可以轻松解决此问题,而无需对所有if... else语句使用if... else语句或echo简写语句告诉echo date('M', strtotime('-n month 2 days'));

2 个答案:

答案 0 :(得分:4)

这是由于PHP如何处理日期数学。你需要确保你总是在本月的第一天工作,以确保不会跳过2月。

DateTime()DateInterval()DatePeriod()让这很容易做到:

$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

您显然可以将$dt->format('F Y')更改为$dt->format('M')以适合您的特定目的。我展示了月份和年份,以证明这是如何运作的。

答案 1 :(得分:0)

感谢John Conde

这就是我使用它的方式:

$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');
    }

这是因为我需要在<span>内内联回调它们。 因此,数组中的第一个值用作:

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

第二个值:

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

等等。

希望这可以帮助那些在这里寻找同样修复的人。

相关问题