Friday, November 30, 2012

To Find a Range of Week for a Date


This is the function for finding a the week of the provided date.

Week of the given date exists.That also separated into month wise weeks for generating weekly reports.

function rangeWeek($datestr) {
    date_default_timezone_set(date_default_timezone_get());
    $date = strtotime($datestr);

    $weekstart = strtotime('last monday', $date);   //Week Start and End date
    $weekend = strtotime('sunday', $date);
    if(date('l',$date) == 'Monday'){                //To find Current day is Monday or Sunday
        $weekstart = $date;
        $weekend = strtotime('sunday', $date);
    }
    //Month Start and End date
    $monthstart =  strtotime("-" . (date("d", $date)-1) . " days", $date);
    $monthend = strtotime("+" . (date("t", $monthstart)-1) . " days", $monthstart);
    $monthstart_minusone = strtotime(date('d-m-Y',$monthstart). ' -1 day');
    $monthend_plusone = strtotime(date('d-m-Y',$monthend). ' + 1 day');

    if($weekend > $monthend){
        $res['week1_starts'] = date('d-m-Y',$weekstart);
        $res['week1_ends'] = date('d-m-Y',$monthend);
        $res['week2_starts'] = date('d-m-Y', $monthend_plusone);
        $res['week2_ends'] = date('d-m-Y',$weekend);
    }else if($weekstart < $monthstart){
        $res['week1_starts'] = date('d-m-Y',$weekstart);
        $res['week1_ends'] = date('d-m-Y',$monthstart_minusone);
        $res['week2_starts'] = date('d-m-Y',$monthstart);
        $res['week2_ends'] = date('d-m-Y',$weekend);
    }else{
        $res['week_starts'] = date('d-m-Y',$weekstart);
        $res['week_ends'] = date('d-m-Y',$weekend);
    }
    return $res;
}
ep(rangeWeek(date('d-m-Y')));