这里是文章模块栏目内容页
PHP获取指定时间段内有几个月 每个月的开始日期和结束日期

在做数据统计表格时候;

需要按一个时间区间统计 区间里的月份数量和每个月份的数据;

这里是php实现计算时间区间里面的月份函数:

/**
 * 获取指定时间段内有几个月,每个月的开始日期和结束日期
 * @return [] [[s:开始日期,e:结束日期],[s:开始日期,e:结束日期]]
 */
function count_months($start_string, $end_string = '')
{       
    $startDate = date('Y-m-d', strtotime($start_string) );
    if(empty($end_string)) {
        $endDate = date('Y-m-d');
    }else{
        $endDate = date('Y-m-d', strtotime($end_string));
    }
 
    $smonth = date("Ym",strtotime($startDate));
    $emonth = date("Ym",strtotime($endDate));
    if($smonth == $emonth){ // 同一月
        $s = date("Y-m-d",strtotime("first Day of this month 00:00:00", strtotime($startDate)));
        $e = date("Y-m-d",strtotime("last Day of this month 23:59:59", strtotime($endDate)));
        $monthList[] =array('s'=>$s, 'e'=> $e);        
    }else{
       
        $month_end    = date("Y-m-d",strtotime("first Day of next month 00:00:00", strtotime($startDate)));            
        $monthList[] =array('s'=>date("Y-m-d", strtotime("first Day of this month 00:00:00", strtotime($startDate))), 
                    'e'=> date("Y-m-d",strtotime("last Day of this month 23:59:59", strtotime($startDate))) ); 
      
        if($month_end >= $endDate){
            $monthList[] = array('s'=> strtotime("last Day of this month 23:59:59", strtotime($startDate)), 
                        'e'=> strtotime("last Day of this month 23:59:59", strtotime($endDate)));
        }else{
            while($month_end <= $endDate){
                $start         = $month_end;
                $month_end     = date("Y-m-d",strtotime("first Day of next month 00:00:00", strtotime($start)));
                if($month_end <= $endDate){
                    $monthList[]  = array('s'=>$start, 'e'=>date("Y-m-d",strtotime("$month_end")));
                }else{
                    $monthList[]  = array('s'=>$start, 'e'=>date("Y-m-d",strtotime("$endDate")));
                }
            }
        }
    }
    return $monthList;
}

好了,本文内容全部结束,感谢您对阅读,希望能帮助到你。


更多栏目
相关内容