我想获取上个月的月份,写了如下代码:
$timestamp = strtotime('last month'); //获取上个月的时间戳
$lastMonth = date('n', $timestamp); //获得上个月的月份
本来程序一直都没问题,后来到了10月31日,发现$lastMonth居然是10。
发现,如果本月的天数大于上月的天数,就会出现问题。
以下代码的结果是一样的!
strtotime('-1 month');
strtotime('last month');
strtotime('-30 days');
正确获取上个月的月份的方法是:
echo date("m-Y", strtotime("first day of previous month"));
echo sprintf("%02d",date("m")-1) . date("-Y");
echo date("m-Y",mktime(0,0,0,date("m")-1,1,date("Y")));