Getting last month's date in php

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

    Incorrect answers are:

    $lastMonth = date('M Y', strtotime("-1 month"));
    $lastDate = date('Y-m', strtotime('last month'));
    

    The reason is if current month is 30+ days but previous month is 29 and less $lastMonth will be the same as current month.

    e.g.

    If $currentMonth = '30/03/2016';
    echo $lastMonth = date('m-Y', strtotime("-1 month")); => 03-2016
    echo $lastDate = date('Y-m', strtotime('last month')); => 2016-03
    

    The correct answer will be:

    echo date("m-Y", strtotime("first day of previous month")); => 02-2016
    echo sprintf("%02d",date("m")-1) . date("-Y"); => 02-2016
    echo date("m-Y",mktime(0,0,0,date("m")-1,1,date("Y"))); => 02-2016
    

提交回复
热议问题