Get previous month value in PHP

后端 未结 5 1751
一生所求
一生所求 2021-01-12 09:38

I have used the below PHP function to get the previous month,

$currmonth = date(\'m\', strtotime(\'-1 month\'));

It was working fine and I

相关标签:
5条回答
  • 2021-01-12 10:14

    You can use OOP with DateTime class and modify method:

    $now = new DateTime();
    $previousMonth = $now->modify('first day of previous month');
    echo $previousMonth->format('m');
    
    0 讨论(0)
  • 2021-01-12 10:21

    strtotime() works accurately. The problem is what you ask it to return.

    "-1 month" is not the same as "previous month". It is the same as "subtract 1 from current month then normalize the result".

    On 2017-05-31, subtracting 1 from current month gets 2017-04-31 which is not a valid date. After normalization, it becomes 2017-05-01, hence the result you get.

    There are more than one way to get the value you need. For example:

    // Today
    $now = new DateTime('now');
    // Create a date interval string to go back to the first day of the previous month
    $int = sprintf('P1M%dD', $now->format('j')-1);
    // Get the first day of the previous month as DateTime
    $fdopm = $now->sub(new DateInterval($int));
    // Verify it works
    echo($fdopm->format('Y-m-d'));
    
    // On 2017-05-31 it should print:
    // 2017-04-01
    
    0 讨论(0)
  • 2021-01-12 10:22

    If you just need to get the month number of previous month, the following should suffice.

    $m = idate("m") - 1;
    // wrap to previous year
    if ($m < 1) {
        $m = 12 - abs($m) % 12;
    }
    

    This works with arbitrary number of subtracted months.

    0 讨论(0)
  • 2021-01-12 10:24

    Try strtotime("first day of last month").

    The first day of is the important part as detailed here.

    0 讨论(0)
  • 2021-01-12 10:26

    Literally ask strtotime for the 'first day of the previous month' this makes sure it selects the correct month:-

    $currmonth = date("m", strtotime("first day of previous month"));
    
    0 讨论(0)
提交回复
热议问题