Getting last month's date in php

前端 未结 18 741
心在旅途
心在旅途 2020-11-29 00:22

I want to get last month\'s date. I wrote this out:

$prevmonth = date(\'M Y\');

Which gives me the current month/year. I can\'t tell if I

18条回答
  •  北海茫月
    2020-11-29 00:30

    The best solution I have found is this:

    function subtracMonth($currentMonth, $monthsToSubtract){
            $finalMonth = $currentMonth;
            for($i=0;$i<$monthsToSubtract;$i++) {
                $finalMonth--;
                if ($finalMonth=='0'){
                    $finalMonth = '12';
                }
    
            }
            return $finalMonth;
    
        }
    

    So if we are in 3(March) and we want to subtract 5 months that would be

    subtractMonth(3,5);

    which would give 10(October). If the year is also desired, one could do this:

    function subtracMonth($currentMonth, $monthsToSubtract){
        $finalMonth = $currentMonth;
        $totalYearsToSubtract = 0;
        for($i=0;$i<$monthsToSubtract;$i++) {
            $finalMonth--;
            if ($finalMonth=='0'){
                $finalMonth = '12';
                $totalYearsToSubtract++;
            }
    
        }
        //Get $currentYear
        //Calculate $finalYear = $currentYear - $totalYearsToSubtract 
        //Put resulting $finalMonth and $finalYear into an object as attributes
        //Return the object
    
    }
    

提交回复
热议问题