PHP計算每月幾周,每周的開始結束日期
因為項目中需要一個每周工作計算的功能,具體日期的算法是,把每月拆分成幾個周,最后一個星期這個月份的天數不夠就補上下個月的。
列如今天8月27星期一,這個月有31天,但是這個星期最后的一天是9月1號,所以要把9月1號加到8月份,然后9月的第一周就要重9月2號開始算,以此類推
下面就直接貼代碼了
//計算某一年某個月有幾周 function get_weekinfo($month) { $weekinfo = array();//創建一個空數組 $end_date = date('d',strtotime($month.' +1 month -1 day'));//計算當前月有多少天 for ($i=1; $i <$end_date ; $i=$i+7) { //循環本月有多少周 $w = date('N',strtotime($month.'-'.$i)); //計算第一天是周幾 $weekinfo[] = array(date('Y-m-d',strtotime($month.'-'.$i.' -'.($w-1).' days')),date('Y-m-d',strtotime($month.'-'.$i.' +'.(7-$w).' days'))); } //當周開始時間 //結束時間 return $weekinfo; }
這是從網上找的代碼 ,但是對3月份不管用,所以我在原來的基礎上做了一下改動
//展示 function generation( $token,$date ) { $uesr = $this->usercache( $token ); $arr = [] ; foreach ($this->get_weekinfo($date) as $k => $v) { //連接上個月的數據去掉 if( date("m",strtotime($v[0])) == date("m",strtotime($date)) ) { $arr[] = $v; } } //月份的最后一天 $lastday = date('Y-m-d', mktime(23, 59, 59, date('m', strtotime($date))+1, 00)); $lastweek = end($arr); //不夠下個月的數據補上 if( strtotime($lastday) > strtotime($lastweek[1]) ) { $newendarr = array( date( 'Y-m-d',strtotime($lastweek[1])+86400 ),date( 'Y-m-d',strtotime($lastweek[1])+(86400*7) ) ); array_push($arr, $newendarr); } try{ //數據插入 foreach ($arr as $ke => $va) { $data['week'] = $ke+1; //第幾周 $data['uid'] = $uesr['uid']; //用戶ID $data['year'] = date('Y',strtotime($date)); //年 $data['month'] = date('m',strtotime($date));//月 //每個星期的開始-結束數據填充 $i = strtotime($va[0]); while ( $i <= strtotime($va[1]) ) { $data['date'] = date('Y-m-d',$i); //年月日 $data['day'] = $this->getTimeWeek( $i );//星期幾 //添加 $this->insertData( $data ); $i = $i+86400; } } return true; } catch (\Exception $e) { return false; } } //獲取星期參數 function getTimeWeek($time) { $day = date("w",$time); return ($day == 0) ? '7' : $day ; }
原理挺簡單的,判斷一個月的數據夠不夠 ,不夠就補上數據 ,用起來也簡單 , 直接輸入 年月就好了, 如:2018-03