php 根据周数获取当周的开始日期与最后日期

/**
     * 根据第几周获取当周的开始日期与最后日期
     * @param int $year 年份 $weeks = get_week($year)
     * @param 如获取第18周的开始日期$weeks[18][0]
     * @param 如获取第18周的最后日期$weeks[18][1]
    */
    static  public function get_week($year) {
        $year_start = $year . "-01-01";
        $year_end = $year . "-12-31";
        $startday = strtotime($year_start);
        if (intval(date('N', $startday)) != '1') {
            $startday = strtotime("next monday", strtotime($year_start)); //获取年第一周的日期
        }
        $year_mondy = date("Y-m-d", $startday); //获取年第一周的日期

        $endday = strtotime($year_end);
        if (intval(date('W', $endday)) == '7') {
            $endday = strtotime("last sunday", strtotime($year_end));
        }

        $num = intval(date('W', $endday));
        for ($i = 1; $i <= $num; $i++) {
            $j = $i -1;
            $start_date = date("Y-m-d", strtotime("$year_mondy $j week "));

            $end_day = date("Y-m-d", strtotime("$start_date +6 day"));

            $week_array[$i] = array (
                str_replace("-",
                "",
                $start_date
            ), str_replace("-", "", $end_day));
        }
        return $week_array;
    }

  以上的第一种方法在 2018-2019会发生错误 转载于:https://www.cnblogs.com/anns/p/5549695.html

 

  //根据第几周获取当周的开始日期与最后日期
  function getWeekDate($year,$weeknum){  
    $firstdayofyear=mktime(0,0,0,1,1,$year);  
    $firstweekday=date('N',$firstdayofyear);  
    $firstweenum=date('W',$firstdayofyear);  
    if($firstweenum==1){  
        $day=(1-($firstweekday-1))+7*($weeknum-1);  
        $startdate=date('Y-m-d',mktime(0,0,0,1,$day,$year));  
        $enddate=date('Y-m-d',mktime(0,0,0,1,$day+6,$year));  
    }else{  
        $day=(9-$firstweekday)+7*($weeknum-1);  
        $startdate=date('Y-m-d',mktime(0,0,0,1,$day,$year));  
        $enddate=date('Y-m-d',mktime(0,0,0,1,$day+6,$year));  
    }  
      
    return array($startdate,$enddate);      
  } 

  这个是正确的

转载于:http://renzhen.iteye.com/blog/939862

posted @ 2017-12-12 15:50  lei12138  阅读(2635)  评论(0编辑  收藏  举报