Getting last month's date in php

前端 未结 18 701
心在旅途
心在旅途 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:29

    It's simple to get last month date

    echo date("Y-n-j", strtotime("first day of previous month"));
    echo date("Y-n-j", strtotime("last day of previous month"));
    

    at November 3 returns

    2014-10-1
    2014-10-31
    
    0 讨论(0)
  • 2020-11-29 00:29

    Use this short code to get previous month for any given date:

    $tgl = '25 january 2012';
    
    $prevmonth = date("M Y",mktime(0,0,0,date("m", strtotime($tgl))-1,1,date("Y", strtotime($tgl))));
    echo $prevmonth;
    

    The result is December 2011. Works on a month with shorter day with previous month.

    0 讨论(0)
  • 2020-11-29 00:30
    $time = mktime(0, 0, 0, date("m"),date("d")-date("t"), date("Y"));
    $lastMonth = date("d-m-Y", $time);
    

    OR

    $lastMonth = date("m-Y", mktime() - 31*3600*24);
    

    works on 30.03.2012

    0 讨论(0)
  • 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
    
    }
    
    0 讨论(0)
  • 2020-11-29 00:32

    Found this one wrong when the previous months is shorter than current.

    echo date("Y-m-d H:i:s",strtotime("-1 month"));
    

    Try on March the 30th and you will get 2012-03-01 instead of 2012-02...

    Working out on better solution...

    0 讨论(0)
  • 2020-11-29 00:34

    You can use strtotime, which is great in this kind of situations :

    $timestamp = strtotime('-1 month');
    var_dump(date('Y-m', $timestamp));
    

    Will get you :

    string '2009-11' (length=7)
    
    0 讨论(0)
提交回复
热议问题