用PHP的date函数获取上一个月的日期时,会存在下面的问题:
$d = date('Y-m-d',strtotime(" -1 month", strtotime("2019-03-31")));
print_r($d);// 输出2019-03-03
如果我们想要按自然月来,希望结果是2019-02-28那怎么办呢?
代码如下:
function lastMonth($nowT,$i){
$lastM1 = date('n',strtotime(" -".$i." month", strtotime("first day of 0 month",$nowT)));
$lastM2 = date('n',strtotime(" -".$i." month", $nowT));
if ($lastM1 != $lastM2){
$expectD = date('Y-m-d',strtotime(" last day of -".$i." month", $nowT));
}else{
$expectD = date('Y-m-d',strtotime(" -".$i." month", $nowT));
}
return $expectD;
}
本文深入探讨了使用PHP的date函数获取上个月日期时遇到的问题,并提供了一种解决方案,确保返回的日期符合自然月份的边界。
&spm=1001.2101.3001.5002&articleId=87807675&d=1&t=3&u=056b9a025f2c403c9b99ae27541f2951)
715

被折叠的 条评论
为什么被折叠?



