PHP计算某时间段内有几个周及某时间为今年第几周函数

2023-12-28 12:41:20
date_default_timezone_set('PRC');
function count_weeks($startDate, $endDate = ''){
  //开始时间
  $startDate = date('Y-m-d', $startDate);
  //结束时间
  if(empty($endDate)) {
    $endDate = date('Y-m-d');
  }else{
    $endDate = date('Y-m-d', $endDate);
  }
  //跨越天数
  $n = (strtotime($endDate)-strtotime($startDate))/86400;
  //判断,跨度小于7天,可能是同一周,也可能是两周
  $endDate = date("Y-m-d",strtotime("$endDate +1 day"));
  if($n<7){
      //查开始时间 在 那周 的 位置
      $day            = date("w",strtotime($startDate))-1;
      //查开始时间  那周 的 周一
      $week_start        = date("Y-m-d",strtotime("$startDate -{$day} day"));
      //查开始时间  那周 的 周末
      $day            = 7-$day;
      $week_end        = date("Y-m-d",strtotime("$startDate +{$day} day"));
      //判断周末时间是否大于时间段的结束时间,如果大于,那就是时间段在同一周,否则时间段跨两周
      if($week_end>=$endDate){        
          $weekList[] =array('s'=>$startDate, 'e'=>date("Y-m-d",strtotime("$endDate -1 day")));
      }else{
          $weekList[] =array('s'=>$startDate, 'e'=>date("Y-m-d",strtotime("$week_end -1 day")));        
          $weekList[] =array('s'=>$week_end, 'e'=>date("Y-m-d",strtotime("$endDate -1 day")));    
      }
  }else{
      //如果跨度大于等于7天,可能是刚好1周或跨2周或跨N周,先找出开始时间 在 那周 的 位置和那周的周末时间
      $day         = date("w",strtotime($startDate))-1;
      $week_start  = date("Y-m-d",strtotime("$startDate -{$day} day"));
      $day         = 7-$day;
      $week_end    = date("Y-m-d",strtotime("$startDate +{$day} day"));
      //先把开始时间那周写入数组
      $weekList[]  =array('s'=>$startDate, 'e'=>date("Y-m-d",strtotime("$week_end -1 day"))); 
      //判断周末是否大于等于结束时间,不管大于(2周)还是等于(1周),结束时间都是时间段的结束时间。
      if($week_end >= $endDate){
          $weekList[] = array('s'=>$week_end, 'e'=>date("Y-m-d",strtotime("$endDate -1 day")));
      }else{
         //N周的情况用while循环一下,然后写入数组
          while($week_end <= $endDate){
              $start         = $week_end;
              $week_end    = date("Y-m-d",strtotime("$week_end +7 day"));
              if($week_end <= $endDate){
                  $weekList[]  = array('s'=>$start, 'e'=>date("Y-m-d",strtotime("$week_end -1 day")));
              }else{
                  $weekList[]  = array('s'=>$start, 'e'=>date("Y-m-d",strtotime("$endDate -1 day")));
              }
          }
      }
  }
  return $weekList;
}

文章来源:https://blog.csdn.net/xu704742366/article/details/135263468
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。