user765081
user765081

Reputation: 261

php get dates for all sundays in a month

I want to be able to come up with a php function that takes in the parameters year, month and the day and returns the dates for the given day in an array.

for eg. lets say the function looks like this:

function get_dates($month, $year, $day)
{
    ....
}

if I call the function as below:

get_dates(12, 2011, 'Sun');

I should get an array containing the values:

2011-12-04
2011-12-11
2011-12-18
2011-12-25

What would the function code look like?

Upvotes: 3

Views: 8813

Answers (4)

Deepak Tyagi
Deepak Tyagi

Reputation: 104

$year="2023";
$month="05";
$start_date = $year."-".$month."-01";
$last_day =  date('Y-m-t',strtotime($start_date));
$total_week_days=array();
for ($i = 0; $i < ((strtotime($last_day) - strtotime($start_date)) / 86400); $i++)
{
if(date('l',strtotime($start_date) + ($i * 86400)) == "Sunday")
{
$total_week_days[]=date('Y-m-d',strtotime($start_date) + ($i * 86400));
}    
}
print_r($total_week_days);

Upvotes: 1

Nole
Nole

Reputation: 847

This is variation of function above. Here you can choose which dates of days in month will be display. For example you want to display all Tuesdays in January 2019.

/*
 * @desc Funtion return array of dates. Array contains dates for custom
 *       days in week.
 * @input integer $year
 * @input integer $month - Month order number (1-12)
 * @input integer $dayOrderNumber - Monday is 1, Tuesday is 2 and Sunday is 7.
 * @return array $customDaysDates - Array of custom day's dates.
 */
function getCustomDaysDatesInMonth($year,$month,$dayOrderNumber){ 

    $date = "$year-$month-01";

    $firstDayInMonth = (integer) date('N',strtotime($date));
    $theFirstCustomDay = ( 7 - $firstDayInMonth + $dayOrderNumber)%7 + 1;
    $lastDayInMonth =  (integer) date('t',strtotime($date));

    $customDaysDates = [];

    for($i=$theFirstCustomDay; $i<=$lastDayInMonth; $i=$i+7 ){
        $customDaysDates[] = $i;
    }

    return  $customDaysDates;
}

$days = getCustomDaysDatesInMonth(2019,1, 2);
print_r($days);

The output should be:

Array ( [0] => 1 [1] => 8 [2] => 15 [3] => 22 [4] => 29 ) 

This mean that 1st, 8th, 15th, 22th and 29th January in 2019 are Tuesdays.

Upvotes: 1

Jerald
Jerald

Reputation: 345

Here is the sample

function getSundays($y,$m){ 
    $date = "$y-$m-01";
    $first_day = date('N',strtotime($date));
    $first_day = 7 - $first_day + 1;
    $last_day =  date('t',strtotime($date));
    $days = array();
    for($i=$first_day; $i<=$last_day; $i=$i+7 ){
        $days[] = $i;
    }
    return  $days;
}

$days = getSundays(2016,04);
print_r($days);

Upvotes: 4

Michael Krelin - hacker
Michael Krelin - hacker

Reputation: 143329

For instance, you may want to find out the weekday of the 1st of month, that would help you to get the first sunday (or whatever day you're looking for), then you go in 7 days increments till the month is over.

Upvotes: 1

Related Questions