'Get all occurrence of specific day in a month

Suppose i have a month June 2014. Now i want to get dates of all Mondays in June month.

like Monday is coming on following days so answer will be like following

2014-06-02
2014-06-09
2014-06-16
2014-06-23
2014-06-30

please do not give be static solution only for June. I need dynamic solution for every month and purely in PHP.

php


Solution 1:[1]

Try this -

<?php
$startDate = "2014-06-01";
$endDate = "2014-06-30";

$startDate = strtotime($startDate);
$endDate = strtotime($endDate);

for($i = strtotime('Monday', $startDate); $i <= $endDate; $i = strtotime('+1 week', $i))
    echo date('l Y-m-d', $i).PHP_EOL;


DEMO:

http://3v4l.org/n4ULA

Solution 2:[2]

Try to create an array with all your date with day on key (with variable $day and $date):

$array = array("Monday" => "2014-06-02", "Tuesday" => "2014-06-03", "Wednesday" => "2014-06-04");

You create a loop to reach all the result :

foreach($array as $key => $value {
    if($key == "Monday")
       echo $value;
}

Solution 3:[3]

Using the above, I created this so you can use variables to define the month, year, and selected weekday.

$month = "6";
$year = "2022";
$weekday = "Tuesday";

$d=cal_days_in_month(CAL_GREGORIAN,$month,$year);
$first_date_of_month = $year."-".$month."-01";
$last_date_of_month = $year."-".$month."-".$d;

$startDate = strtotime($first_date_of_month);
$endDate = strtotime($last_date_of_month);

for($i = strtotime($weekday, $startDate); $i <= $endDate; $i = strtotime('+1 week', $i))
    echo "<br />". date('l Y-m-d', $i).PHP_EOL;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Dev'Hamz
Solution 3 Sam Horowitz