您的当前位置:首页>全部文章>文章详情

php的strtotime('+1 month'),一个月的最后一天bug

发表于:2024-08-12 12:03:10浏览:173次 TAG: #时间戳 #日期 收藏

php的strtotime(’+1 month’)函数,如果今天是1月31号,

使用strtotime(’+1 month’)函数变成3月3号,

而我的结果是想获得2月份最后一天的日期,也就是2月28号,

下面这段代码可以解决这个bug

 

$extime ='1706544000';
$nexttime = App::nextmonth($extime);


class App 
{
	
	static function nextmonth($extime,$last = ''){        

		//获取当前第几天
        $ex_d = date("d",$extime);

        // 获取当前月的第一天
		$exDate = date('Y-m-01',$extime);		

		// 获取下个月第一天
		$next_01 = date('Y-m-d', strtotime("+1 month", strtotime($exDate)));
		$next_y=date("Y",strtotime($next_01));
		$next_m=date("m",strtotime($next_01));		

		//下个月总天数
        $next_lastDay = cal_days_in_month(CAL_GREGORIAN,$next_m,$next_y);
        // $next_lastDay = date('t', strtotime($next_01));// 获取下个月最后一天


		if($ex_d>$next_lastDay or $last == 1 or $ex_d == 31){ 
            $nextday = $next_y."-".$next_m."-".$next_lastDay;  
            $nexttime = strtotime($nextday); 
        }else{
            $nexttime = strtotime("+1 month",$extime); 
        }
		     
        return $nexttime;

    }
}

 

1、获取当前月第一天,当前时间第几天

2、获取下月第一天,下月总天数(最后一天)

3、判断,当前天数>下月总天数,表示: 下个月,天数变少了,则取下月最后一天

 

这里主要用到的是 cal_days_in_month() 函数,返回指定年份和日历的一个月中的天数。

注意:该函数在 PHP5之后,已被废除,建议用 date('t',time)

 

语法

cal_days_in_month(calendar,month,year);

 

参数 描述

calendar 必需。规定要使用的历法。请参阅 PHP Calendar 常量。

month 必需。规定选定历法中的月。

year 必需。规定选定历法中的年。

 

示例

<?php
$d=cal_days_in_month(CAL_GREGORIAN,10,2005);
echo "There was $d days in October 2005";
?>

 

 

 

Hi 小闻

可以咨询展会的任何问题哦 关闭