I have $fromdate
and $todate
variables. I want a function that can calculate the dates of each Sunday existing in between $fromdate
and $todate
in PHP.
Asked
Active
Viewed 1.3k times
3

Welbog
- 59,154
- 9
- 110
- 123
-
2This seems trivial to the point that it might be homework. Not sure, though. – Welbog Jul 02 '09 at 12:35
-
Hmm...if I remember correctly, I think this is a Project Euler question. – Beska Jul 02 '09 at 12:46
4 Answers
11
Assuming these are date objects, start at $fromdate, add one day to it, until that date is Sunday, and as long as the date is before $todate. Add 7 days to each Sunday you find, add that date and continue as long as the new date is before $todate. Keep track of each date found this way.

tvanfosson
- 524,688
- 99
- 697
- 795
8
Use this function:
function getDateForSpecificDayBetweenDates($startDate, $endDate, $weekdayNumber)
{
$startDate = strtotime($startDate);
$endDate = strtotime($endDate);
$dateArr = array();
do
{
if(date("w", $startDate) != $weekdayNumber)
{
$startDate += (24 * 3600); // add 1 day
}
} while(date("w", $startDate) != $weekdayNumber);
while($startDate <= $endDate)
{
$dateArr[] = date('Y-m-d', $startDate);
$startDate += (7 * 24 * 3600); // add 7 days
}
return($dateArr);
}
The function call to get dates for all Sunday's in year 2010:
$dateArr = getDateForSpecificDayBetweenDates('2010-01-01', '2010-12-31', 0);
print "<pre>";
print_r($dateArr);
The reuslt:
Array
(
[0] => 2010-01-03
[1] => 2010-01-10
[2] => 2010-01-17
[3] => 2010-01-24
[4] => 2010-01-31
[5] => 2010-02-07
................
................
................
[47] => 2010-11-28
[48] => 2010-12-05
[49] => 2010-12-12
[50] => 2010-12-19
[51] => 2010-12-26
)

DXB-DEV
- 547
- 1
- 7
- 18
-
2$startDate += (7 * 24 * 3600); // add 7 days should be: $startDate = strtotime("+1 week", $startDate); // add 7 days – Bokw Aug 31 '12 at 18:27
-
-
@dxb_dev how to count Saturday and Sunday both current output is only Sunday. Thanks – Muddasir Abbas Aug 24 '15 at 07:06
-
hi there, nice answer ... can you guide me .. how can apply 2 weekends ... i try it .. but its not working – deemi-D-nadeem Sep 20 '17 at 12:33
3
Try this
function getDateForSpecificDayBetweenDates($start, $end, $weekday = 0){
$weekdays="Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday";
$arr_weekdays=split(",", $weekdays);
$weekday = $arr_weekdays[$weekday];
if(!$weekday)
die("Invalid Weekday!");
$start= strtotime("+0 day", strtotime($start) );
$end= strtotime($end);
$dateArr = array();
$friday = strtotime($weekday, $start);
while($friday <= $end)
{
$dateArr[] = date("Y-m-d", $friday);
$friday = strtotime("+1 weeks", $friday);
}
$dateArr[] = date("Y-m-d", $friday);
return $dateArr;
}
Here's how this function can be called...
$dateArr = getDateForSpecificDayBetweenDates("Today", "+1 year", 0); // 0 Sun, 1 Mon, etc.
$start
and $end
dates will take anything that strtotime()
supports.

stealthyninja
- 10,343
- 11
- 51
- 59

Rajesh Soni
- 71
- 4