php指定时间 n天,PHP实现指定时间的n月之前的这一天的两种算法

/**

*根据$endtime,返回指定$monthes月之前的日

*/

function severalMonthAgo($endtime,$monthes){

if (!$endtime) {

return false;

}

if (!is_int($monthes) || $monthes <=0) {

return false;

}

$m = date("m",$endtime);

$y = date("Y",$endtime);

$d = date("d",$endtime);

$year = floor($monthes/12);

$monthes_mod = $monthes%12;

if($year == 0){

//<12个月

if($m < $monthes){

//当前月份小于n月前

$res_y = $y-1;

$res_m = 12-($monthes-$m);

$t = date("t",strtotime($res_y."-".$res_m."-01"));

if($d

$res_d = $d;

}else{

$res_d = $t;

}

}elseif($m == $monthes){

$res_y = $y-1;

$res_m = 12;

$t = date("t",strtotime($res_y."-".$res_m."-01"));

if($d

$res_d = $d;

}else{

$res_d = $t;

}

}elseif($m>$monthes){

$res_y = $y;

$res_m = $m-$monthes;

$t = date("t",strtotime($res_y."-".$res_m."-01"));

if($d

$res_d = $d;

}else{

$res_d = $t;

}

}

}elseif($year>0){

$y = $y-$year;

$monthes = $monthes_mod;

if($m < $monthes){

//当前月份小于n月前

$res_y = $y-1;

$res_m = 12-($monthes-$m);

$t = date("t",strtotime($res_y."-".$res_m."-01"));

if($d

$res_d = $d;

}else{

$res_d = $t;

}

}elseif($m == $monthes){

$res_y = $y-1;

$res_m = 12;

$t = date("t",strtotime($res_y."-".$res_m."-01"));

if($d

$res_d = $d;

}else{

$res_d = $t;

}

}elseif($m>$monthes){

$res_y = $y;

$res_m = $m-$monthes;

$t = date("t",strtotime($res_y."-".$res_m."-01"));

if($d

$res_d = $d;

}else{

$res_d = $t;

}

}

}

return strtotime($res_y."-".$res_m."-".$res_d);

}

/**

*根据$endtime,返回指定$monthes月之前的日

*/

function severalMonthAgoEx($endtime,$monthes){

if (!$endtime) {

return false;

}

if (!is_int($monthes) || $monthes <=0) {

return false;

}

$m = date("m",$endtime);

$y = date("Y",$endtime);

$d = date("d",$endtime);

$year = floor($monthes/12);

$monthes_mod = $monthes%12;

$y -= $year;

//$year =0或>0;

//$monthes_mod =0或>0或

if ($year>0) {

if ($monthes_mod>0) {

$m_diff = 12+$m-$monthes_mod;

$m_diff_div = floor($m_diff/12);

$m_diff_mod = $m_diff%12;

if ($m_diff_div > 0) {

$res_y = $y;

$res_m = $m_diff_mod;

}elseif ($m_diff_div == 0) {

$res_y = $y -1;

$res_m = $m_diff_mod;

}

}elseif ($monthes_mod==0) {

//整除

$res_y = $y;

$res_m = $m;

}

}elseif ($year == 0) {

$m_diff = 12+$m-$monthes_mod;

$m_diff_div = floor($m_diff/12);

$m_diff_mod = $m_diff%12;

if ($m_diff_div > 0) {

$res_y = $y;

}elseif ($m_diff_div == 0) {

$res_y = $y -1;

}

$res_m = $m_diff_mod;

}

$t = date("t",strtotime($res_y."-".$res_m."-01"));

if($d

$res_d = $d;

}else{

$res_d = $t;

}

return strtotime($res_y."-".$res_m."-".$res_d);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值