/**
* 返回某个时间几月前或及月后的时间戳
* @$datetime 指定时间戳
* @$num 增减月份(1,-2)
* @return datetime
*/
public static function getEveryMonth($datetime,$num){
$year_month = date("Y-m",$datetime);
$time_day = date("d",$datetime);
$H = date("H",$datetime);
$i = date("i",$datetime);
$s = date("s",$datetime);
if($num>0){
$act = "+".abs($num)." month";
}else{
$act = "-".abs($num)." month";
}
$time = strtotime($act,strtotime($year_month));
$time_str = date("Y-m-d",$time);
if(date("t",$time)>$time_day){
$return_time = mktime($H,$i,$s,date("m",$time),date("d",$time),date("Y",$time));
}else{
$return_time = mktime($H,$i,$s,date("m",$time),date("t",$time),date("Y",$time));
}
return $return_time;
}
/****
vDate 是指定时间,如2014-01-01格式,如果为空就是当前时间
vNum 是加减的数量,如果是负数就是提前,正数就是延后
vType 是加减类型,'day','month','year'
*/
function DateCount($vDate,$vNum,$vType){
if(empty($vDate)){
$vDate=date("Y-m-d");
}
$vNum=intval($vNum);
if(empty($vNum)){
return $vDate;
}
$vNumstr="+".abs($vNum);
if($vNum<0){
$vNumstr="-".abs($vNum);
}
$time=strtotime($vDate);
if($vType=="year"){
$time=strtotime("$vNumstr years",$time);
}elseif($vType=="month"){
$time=strtotime("$vNumstr month",$time);
}elseif($vType=="day"){
$time=strtotime("$vNumstr days",$time);
}else{
return false;
}
return date("Y-m-d",$time);
}
function datecount($vdate,$vnum,$vtype){
$day = date('j',strtotime($vdate));
$month = date('n',strtotime($vdate));
$year = date('Y',strtotime($vdate));
switch($vtype){
case 'day':
if($vnum >= 0){
$day = $day + abs($vnum);
}else{
$day = $day - abs($vnum);
}
break;
case 'month':
if($vnum >= 0){
$month = $month+ abs($vnum);
}else{
$month = $month- abs($vnum);
}
$next = getDays($month,$year);//获取变换后月份的总天数
if($next<$day){
$day = $next;
}
break;
case 'year':
if($vnum >= 0){
$year = $year+ abs($vnum);
}else{
$year = $year - abs($vnum);
}
break;
default :
break;
}
$time = mktime(0,0,0,$month,$day,$year);
return date('Y-m-d',$time);
}
function getDays($month,$year){//获取给定月份的天数
switch($month){
case '1':
case '3':
case '5':
case '7':
case '8':
case '10':
case '12':
return 31;
break;
case '4':
case '6':
case '9':
case '11':
return 30;
break;
case '2':
if(($year%4==0 && $year%100!=0) || $year%400==0){//整百的年份要同时满足400的倍数才算闰年
return 29;
}else{
return 28;
}
break;
}
}
echo datecount('2000-01-31',1,'month');
亲测,可用,关键逻辑是21-23行
function datecount($vdate,$vnum,$vtype){
$day = date('d',strtotime($vdate));
$month = date('n',strtotime($vdate));
$year = date('Y',strtotime($vdate))
switch($vtype){
case 'day':
if($vnum >= 0){
$day = $day + abs($vnum);
}else{
$day = $day - abs($vnum);
}
break;
case 'month':
if($vnum >= 0){
$day = $month+ abs($vnum);
}else{
$day = $month- abs($vnum);
}
break;
case 'year':
if($vnum >= 0){
$day = $year+ abs($vnum);
}else{
$day = $year - abs($vnum);
}
break;
default :
break;
}
$time = mktime(0,0,0,$month,$year,$year);
return date('Y-m-d',$time)
}