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

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

    I think you've found a bug in the strtotime function. Whenever I have to work around this, I always find myself doing math on the month/year values. Try something like this:

    $LastMonth = (date('n') - 1) % 12;
    $Year      =  date('Y') - !$LastMonth;
    
    0 讨论(0)
  • 2020-11-28 08:35

    If a DateTime solution is acceptable this snippet returns the year of last month and month of last month avoiding the possible trap when you run this in January.

    function fn_LastMonthYearNumber()
    {
     $now = new DateTime();
     $lastMonth = $now->sub(new DateInterval('P1M'));
     $lm= $lastMonth->format('m');
     $ly= $lastMonth->format('Y');
     return array($lm,$ly);
    }
    
    0 讨论(0)
  • 2020-11-28 08:41

    if the day itself doesn't matter do this:

    echo date('Y-m-d', strtotime(date('Y-m')." -1 month"));
    
    0 讨论(0)
提交回复
热议问题