PHP实现周和月起止时间计算方法


当前周的起止时间计算

public function getWeekend(){
        $date=date("Y-m-d");  //当前日期
        $first=1; //$first =1 表示每周星期一为开始日期 0表示每周日为开始日期
        $w=date('w',strtotime($date));  //获取当前周的第几天 周日是0周一到周六是1-6
        $now_start=date('Y-m-d',strtotime("$date -".($w==0 ? 6 : $w - $first).' days')); //获取本周开始日期,如果$w是0,则表示周日,减去6天
        $now_end=date('Y-m-d',strtotime("$now_start +6 days"));  //本周结束日期
        $week[]=array($now_start,$now_end);
        return $week;
    }

运行结果:
weekends演示

当前月的起止时间计算

    public function getMonth(){
        $date = date("Y-m-d");
        $start_date = date('Y-m-d', mktime(00, 00, 00, date('m', strtotime($date)), 01));
        $end_date = date('Y-m-d', mktime(23, 59, 59, date('m', strtotime($date))+1, 00));
        $month[]=array($start_date,$end_date);
        return $month;
    }

运行结果:
months运行结果

当前周往后的指定周数的起止时间

public function getWeekends(){
    header('Content-type: text/html; charset=utf-8');
    $date=date("Y-m-d");  //当前日期
    $first=1; //$first =1 表示每周星期一为开始日期 0表示每周日为开始日期
    $w=date('w',strtotime($date));  //获取当前周的第几天 周日是0周一到周六是1-6 
    $now_start=date('Y-m-d',strtotime("$date -".($w==0 ? 6 : $w - $first).' days')); //获取本周开始日期,如果$w是0,则表示周日,减去6天
    $now_end=date('Y-m-d',strtotime("$now_start +6 days"));  //本周结束日期

    $weekEndCnt=1;
    $weekStCnt=7;

    echo '第0开始日期:'.$now_start.'<br />';
    echo '第0结束日期:'.$now_end.'<br />';
    echo "<br />";

    for($i=1;$i<10;$i++){
    $last_start=date('Y-m-d',strtotime("$now_end + ".$weekEndCnt." days"));//开始日期
    $last_end=date('Y-m-d',strtotime("$now_end + ".$weekStCnt." days")); //结束日期    
    echo '第'.$i.'开始日期:'.$last_start.'<br />';
    echo '第'.$i.'结束日期:',$last_end,'<br />';
    $weekStCnt+=7;
    $weekEndCnt+=7;
    echo "<br />";
    }
}

运行结果:
这里写图片描述

指定月的每周的起止日期

public function getWeekendsByMonths(){
   $current_year="2017";//指定日期的年份
   $current_month="12";//指定日期的月份
  //该月第一天
  $firstday = strtotime($current_year.'-'.$current_month.'-01');
  //该月的第一周有几天
  $firstweekday = (7 - date('N',$firstday) +1);
  //计算该月第一个周一的时间
  $starttime = $firstday-3600*24*(7-$firstweekday);
  //该月的最后一天
  $lastday = strtotime($current_year.'-'.$current_month.'-01'." +1 month -1 day");
  //该月的最后一周有几天
  $lastweekday = date('N',$lastday);
  //该月的最后一个周末的时间
  $endtime = $lastday-3600*24*($lastweekday%7);
  $step = 3600*24*7;//步长值
  $week_arr = array();
  for ($i=$starttime; $i<$endtime; $i= $i+3600*24*7){
    $week_arr[] = array('Start'=>date('Y-m-d',$i),"End"=>date('Y-m-d',$i+3600*24*6));
  }
  var_dump($week_arr);

 }

运行结果:
这里写图片描述

posted @ 2017-12-05 00:53  Newtol  阅读(900)  评论(0编辑  收藏  举报