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

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

    strtotime have second timestamp parameter that make the first parameter relative to second parameter. So you can do this:

    date('Y-m', strtotime('-1 month', time()))
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-11-28 08:19
    date("m-Y", strtotime("-1 months")); 
    

    would solve this

    0 讨论(0)
  • 2020-11-28 08:20

    Have a look at the DateTime class. It should do the calculations correctly and the date formats are compatible with strttotime. Something like:

    $datestring='2011-03-30 first day of last month';
    $dt=date_create($datestring);
    echo $dt->format('Y-m'); //2011-02
    
    0 讨论(0)
  • 2020-11-28 08:26

    This is because the previous month has less days than the current month. I've fixed this by first checking if the previous month has less days that the current and changing the calculation based on it.

    If it has less days get the last day of -1 month else get the current day -1 month:

    if (date('d') > date('d', strtotime('last day of -1 month')))
    {
        $first_end = date('Y-m-d', strtotime('last day of -1 month'));
    }
    else
    {
        $first_end = date('Y-m-d', strtotime('-1 month'));
    }
    
    0 讨论(0)
  • 2020-11-28 08:29

    If you want the previous year and month relative to a specific date and have DateTime available then you can do this:

    $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
    
    0 讨论(0)
提交回复
热议问题