php求兩個日期之間每個月的開始和結束時間

function timeBetween($start, $end){
  $d_s = strtotime(date('Y-m', $start));
  $d_e = strtotime(date('Y-m', $end));

  $num = 1; 
  $dates = array();
 
     while ($start<=$end){
   if($d_s == $d_e){
    $dates[] = array(
     'time_start' => date('Y-m-d',$start),
     'time_end' => date('Y-m-d',$end),
    );
    break;
   }else{
    if($num == 1){
     $dates[] = array(
      'time_start' => date('Y-m-d',$start),
      'time_end' => date('Y-m-t',$start),
     );
    }else{
     $dates[] = array(
      'time_start' => date('Y-m' . '-01',$start),
      'time_end' => date('Y-m-t',$start),
     ); 
    }
    $start = strtotime('+1 month',$start); 
   }
   $num ++;
     }
  $pop_ele = array_pop($dates);
  $pop_ele['time_end'] = date('Y-m-d',$end);
 
  array_push($dates, $pop_ele);
  return $dates;
 }

 

測試:
var_dump(timeBetween(strtotime('2005-02-01'),strtotime('2005-02-05')));

發佈了20 篇原創文章 · 獲贊 6 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章