1. 程式人生 > >PHP獲取當前月份的前一個月、後一個月

PHP獲取當前月份的前一個月、後一個月

在某次開發中,需要對月份進行處理,獲取到前一個月或者後一個月,開始使用

date("Ym", strtotime("-1 month")) 

後來發現,這種方法會有問題,在月份有31天的時候,比如7月31日,會出現 date("Ym", strtotime("-1 month")) 這個是時間也是201207與date("Ym")結果一樣。這樣就會導致在這天產生很多問題。



 後來只能用這樣 的方法

function GetMonth($sign="1")
{
    //得到系統的年月
    $tmp_date=date("Ym");
    //切割出年份
    $tmp_year=substr($tmp_date,0,4);
    //切割出月份
    $tmp_mon =substr($tmp_date,4,2);
    $tmp_nextmonth=mktime(0,0,0,$tmp_mon+1,1,$tmp_year);
    $tmp_forwardmonth=mktime(0,0,0,$tmp_mon-1,1,$tmp_year);
    if($sign==0){
        //得到當前月的下一個月 
        return $fm_next_month=date("Ym",$tmp_nextmonth);        
    }else{
        //得到當前月的上一個月 
        return $fm_forward_month=date("Ym",$tmp_forwardmonth);         
    }
}