How to get previous month and year relative to today, using strtotime and date?

前端 未结 15 987
情书的邮戳
情书的邮戳 2020-11-28 07:48

I need to get previous month and year, relative to current date.

However, see following example.

// Today is 2011-03-30
echo date(\'Y-m-d\', strtotim         


        
15条回答
  •  心在旅途
    2020-11-28 08:31

    function getOnemonthBefore($date){
        $day = intval(date("t", strtotime("$date")));//get the last day of the month
        $month_date = date("y-m-d",strtotime("$date -$day days"));//get the day 1 month before
        return $month_date;
    }
    

    The resulting date is dependent to the number of days the input month is consist of. If input month is february (28 days), 28 days before february 5 is january 8. If input is may 17, 31 days before is april 16. Likewise, if input is may 31, resulting date will be april 30.

    NOTE: the input takes complete date ('y-m-d') and outputs ('y-m-d') you can modify this code to suit your needs.

提交回复
热议问题