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

前端 未结 15 976
情书的邮戳
情书的邮戳 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:18

    //return timestamp, use to format month, year as per requirement
    function getMonthYear($beforeMonth = '') {
        if($beforeMonth !="" && $beforeMonth >= 1) {
            $date = date('Y')."-".date('m')."-15";
            $timestamp_before = strtotime( $date . ' -'.$beforeMonth.' month' );
            return $timestamp_before;
        } else {
            $time= time();
            return $time;
        }
    }
    
    
    //call function
    $month_year = date("Y-m",getMonthYear(1));// last month before  current month
    $month_year = date("Y-m",getMonthYear(2)); // second last month before current month
    

提交回复
热议问题