2014-03-29 49 views
0

我正在繪製條形圖,x軸上的值是過去一年中的月份。例如,這是2014年3月;所以x軸上的值從2013年4月到2014年3月是當前月份。顯示從當前日期開始的過去11個月的列表

我使用echo date('M');來打印當前月份和echo date('M', strtotime(' -1 month'));echo date('M', strtotime(' -2 month'));等等以獲得所有前幾個月。

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

'Feb'應該是'印''Mar'。我認爲這是因爲二月有28天。

是否有一個簡單的解決方案,而不必使用if... else語句或if... else所有echo語句的速記語句告訴它echo date('M', strtotime('-n month 2 days'));

+2

您可以從獲取本月第一天的時間戳開始 - 然後從中減去幾個月,這應該避免月份有不同天數的問題。 – CBroe

回答

3

這是由於PHP如何處理日期數學。您需要確保您始終在本月的第一天工作,以確保二月不會被跳過。

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')以滿足您的特定目的。我展示了月份和年份,以說明這是如何工作的。

0

感謝約翰·孔德

這是我如何使用它:

$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

等。

希望這可以幫助在此尋找相同修復程序的人。

+0

僅供參考,當有人爲您提供您正在尋找的解決方案時,您不應該爲發佈您如何使用其解決方案發布正確答案。 –

+0

對不起。我不知道發生了什麼。我用我的電腦留下了我的小表弟@JohnConde – ThisBoyPerforms

+0

我們都知道小表兄弟像綠色的複選標記;) –

相關問題