7 April 2014

How to get all days of week from given date.

Hello!,

Here i have added php code for getting all days of week from given date.
Following function will help you to get this.
/**
 * Get all days of week.
 * @param date $date
 */
function getDaysOfWeek( $date )
{
    list($day, $month, $year) = explode( "-", date('d-m-Y', strtotime($date)) );
    // Get the weekday of the given date
    $wkday = date('l', strtotime($date));

    switch($wkday)
    {
        case 'Sunday': $numDaysToSun = 0; break;
        case 'Monday': $numDaysToSun = 1; break;
        case 'Tuesday': $numDaysToSun = 2; break;
        case 'Wednesday': $numDaysToSun = 3; break;
        case 'Thursday': $numDaysToSun = 4; break;
        case 'Friday': $numDaysToSun = 5; break;
        case 'Saturday': $numDaysToSun = 6; break;
    }
    // Timestamp of the sunday for that week
    $sunday = mktime('0','0','0', $month, $day-$numDaysToSun, $year);
    $seconds_in_a_day = 86400;

    // Get date for 7 days from Sunday (inclusive)
    for($i=0;$i<7;$i + +)
    {
        $day_name = date('l', $sunday+($seconds_in_a_day*$i));
        $dates[$day_name] = date('Y-m-d', $sunday+($seconds_in_a_day*$i));
    }
    return $dates;
}

Example:-
$weekdays = getDaysOfWeek(date('d-m-Y'));
echo "<pre>";
var_dump($weekdays);
exit;

/* This will output something like this:-
array(7) {
    ["Sunday"]=>
    string(10) "2014-04-06"
    ["Monday"]=>
    string(10) "2014-04-07"
    ["Tuesday"]=>
    string(10) "2014-04-08"
    ["Wednesday"]=>
    string(10) "2014-04-09"
    ["Thursday"]=>
    string(10) "2014-04-10"
    ["Friday"]=>
    string(10) "2014-04-11"
    ["Saturday"]=>
    string(10) "2014-04-12"
}

Have Fun!

No comments:

Post a Comment