Find weekly periods (starting on a Monday) for a month

前端 未结 3 1393
南方客
南方客 2020-12-09 14:13

I\'m trying to find the weekly periods for a given month and year. Dates should start on a Monday and end on a Sunday. If the 1st of the month is a Sunday (Ex May 2011), it

3条回答
  •  长情又很酷
    2020-12-09 14:50

    this works perfect!!! phpfiddle here

    ';
    foreach ($weeks as $week){
       echo fDate($week['start']).' '.fDate($week['end']).'
    '; } echo 'To: '.fDate($end).'
    '; /* outputs this: From: Thu 2012-09-06 Thu 2012-09-06 Sun 2012-09-09 Mon 2012-09-10 Sun 2012-09-16 Mon 2012-09-17 Sun 2012-09-23 Mon 2012-09-24 Wed 2012-09-26 To: Wed 2012-09-26 */ // $start and $end must be unix timestamps (any range) // returns an array of arrays with 'start' and 'end' elements set // for each week (or part of week) for the given interval // return values are also in timestamps function generateweeks($start,$end){ $ret = array(); $start = E2D($start); $end = E2D($end); $ns = nextSunday($start); while(true){ if($ns>=$end) {insert($ret,$start,$end);return $ret;} insert($ret,$start,$ns); $start = $ns +1; $ns+=7; } } // helper function to append the array and convert back to unix timestamp function insert(&$arr, $start, $end){$arr[] = array('start'=>D2E($start), 'end'=>D2E($end));} // recives any date on CD format returns next Sunday on CD format function nextSunday($Cdate){return $Cdate + 6 - $Cdate % 7;} // recives any date on CD format returns previous Monday on CD format // finaly not used here function prevMonday($Cdate){return $Cdate - $Cdate % 7;} // recives timestamp returns CD function E2D($what){return floor($what/86400)+2;} // floor may be optional in some circunstances // recives CD returns timestamp function D2E($what){return ($what-2)*86400;} // 24*60*60 // just format the timestamp for output, you can adapt it to your needs function fDate($what){return date('D Y-m-d',$what);}

提交回复
热议问题