当前位置 : 主页 > 网络编程 > PHP >

php获取两个日期间之间的月份

来源:互联网 收集:自由互联 发布时间:2021-06-30
$start_date = '2014-09-08';$end_date = '2015-10-09'; $start_arr = explode("-", $start_date);$end_arr = explode("-", $end_date); $start_year = intval($start_arr[0]);$start_month = intval($start_arr[1]); $end_year = intval($end_arr[0]);$end_m
 
$start_date = '2014-09-08';
$end_date = '2015-10-09';
  
$start_arr = explode("-", $start_date);
$end_arr = explode("-", $end_date);
  
$start_year = intval($start_arr[0]);
$start_month = intval($start_arr[1]);
  
$end_year = intval($end_arr[0]);
$end_month = intval($end_arr[1]);
  
$diff_year = $end_year-$start_year;
  
$month_arr = [];
//获取月份
if($diff_year == 0){
    for($month = $start_month;$month<=$end_month;$month++){
        $month_arr[] = $start_year.'-'.$month.'-1';
    }
} else {
    for($year =$start_year;$year<=$end_year;$year++){
        if($year == $start_year){
            for($month = $start_month;$month<=12;$month++){
                $month_arr[] = $year.'-'.$month.'-1';
            }
        }elseif($year==$end_year){
            for($month = 1;$month<=$end_month;$month++){
                $month_arr[] = $year.'-'.$month.'-1';
            }
        }else{
            for($month = 1;$month<=12;$month++){
                $month_arr[] = $year.'-'.$month.'-1';
            }
        }
    }   
}
echo "<pre>";
print_r($month_arr);
  
Array
(
    [0] => 2014-9-1
    [1] => 2014-10-1
    [2] => 2014-11-1
    [3] => 2014-12-1
    [4] => 2015-1-1
    [5] => 2015-2-1
    [6] => 2015-3-1
    [7] => 2015-4-1
    [8] => 2015-5-1
    [9] => 2015-6-1
    [10] => 2015-7-1
    [11] => 2015-8-1
    [12] => 2015-9-1
    [13] => 2015-10-1
)

网友评论