Under PHP get the date of last month next month and this month of strtotime date

  • 2020-12-26 05:37:50
  • OfStack

Write programs today, suddenly discovered a long time ago write access to the function, the number of days in switch version of the classic, but the time of days last month, I just put the month - 1, estimate was too sleepy, then to see the kind of creepy feeling, want to handle one originally, but do think there must be super convenient way, and found the following version, made 1 small change.

Date of this month:


function getMonth($date){
     $firstday = date("Y-m-01",strtotime($date));
     $lastday = date("Y-m-d",strtotime("$firstday +1 month -1 day"));
     return array($firstday,$lastday);
 }

$firstday is the first day of the month. If $date is 2014-2, then $firstday will be 2014-02-01. Then add 1 month to $firstday to be 2014-03-01 and subtract 1 day to be 2014-02-28.

Get last month date:


function getlastMonthDays($date){
     $timestamp=strtotime($date);
     $firstday=date('Y-m-01',strtotime(date('Y',$timestamp).'-'.(date('m',$timestamp)-1).'-01'));
     $lastday=date('Y-m-d',strtotime("$firstday +1 month -1 day"));
     return array($firstday,$lastday);
 }

Last month's date needs to get a timestamp first, and then OK on month -1. Super smart date() will convert 2014-0-1 to 2013-12-01, which is awesome.

Get next month date:


function getNextMonthDays($date){
    $timestamp=strtotime($date);
    $arr=getdate($timestamp);
    if($arr['mon'] == 12){
        $year=$arr['year'] +1;
        $month=$arr['mon'] -11;
        $firstday=$year.'-0'.$month.'-01';
        $lastday=date('Y-m-d',strtotime("$firstday +1 month -1 day"));
    }else{
        $firstday=date('Y-m-01',strtotime(date('Y',$timestamp).'-'.(date('m',$timestamp)+1).'-01'));
        $lastday=date('Y-m-d',strtotime("$firstday +1 month -1 day"));
    }
    return array($firstday,$lastday);
}

The code for the next month date looks a little bit longer, because date() won't rotate like 2014-13-01 and it will go straight back to 1970, so we need to deal with the problem of the next December in front, except that the month +1 is OK.

All in all, it's convenient. The date function is too powerful.


Related articles: