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

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

Asked on December 27, 2018 in PHP.
Add Comment


  • 3 Answer(s)

    Try to use the DateTime class. This will be congruous strttotime, like this.

    $datestring='2011-03-30 first day of last month';
    $dt=date_create($datestring);
    echo $dt->format('Y-m'); //2011-02
    
    Answered on December 27, 2018.
    Add Comment

    One can simply use this one line code,

    echo date('Y-m-d', strtotime(date('Y-m')." -1 month"));
    
    
    Answered on December 27, 2018.
    Add Comment

    To get the previous year and month , we have to use the function called DateTime(),

    $d = new DateTime('2013-01-01', new DateTimeZone('UTC'));
    $d->modify('first day of previous month');
    $year = $d->format('Y'); //2012
    $month = $d->format('m'); //12
    
    Answered on December 27, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.