PHP的日期时间月份-1为什么不返回02?

时间:2019-03-29 12:04:13

标签: php datetime

$lastMonth = (new DateTime())->modify('-1 month')->format('Y-m');
echo $lastMonth;

为什么会返回2019-03?

1 个答案:

答案 0 :(得分:2)

  

-1个月可能会产生错误的结果,因为某些月份有31天。

使用last day of previous month

$d = new DateTime( date("Y-m-d") );
$d->modify('last day of previous month' );
echo $d->format( 'Y-m' );