dongzai3139 2017-03-29 07:08
浏览 113
已采纳

PHP日期在减去一个月后返回错误的月份

Current Date is 29th March 2017

When I subtract 2 months using PHP and I get January

$prevmonth = date('M', strtotime('-2 months'));
echo $prevmonth;

But when I subtract 1 month it gives March

$prevmonth = date('M', strtotime('-1 months'));
echo $prevmonth;
  • 写回答

2条回答 默认 最新

  • dtah63820 2017-03-29 07:20
    关注

    strtotime() uses 30 day months and there are only 28 in days in February (this year) so will not yield a valid date in February. You could use the current day d or j and subtract that which will always put you in the previous month (-29 days):

    $prevmonth = date('M', strtotime('-' . date('d') . ' days'));
    

    This will get December from January as well.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?