This is the function I\'m trying to write:
function getWednesdays($month, $year) {
// Returns an array of DateTimes representing all Wednesdays this month
With PHP earlier than 5.3 this solution doesn't work. Seems, First Day Time stamp is greater than the last day time stamp, which eventually terminate the loop in first go.
As PHP calculates time differences at midnight, this solution does not work when the month starts on the day in question. And for some cases does not work for the last day either.
I've sorted out these problems in following code. And this code can be used for any day of week.
The solution was created with the help of Eli's code in this question: Get the First or Last Friday in a Month
///// code starts here /////
function getWeekDates($year, $month, $day){
$tsInMonth = strtotime("$year-$month");
$monthNumber = (int)date("m",$tsInMonth);
$Names = array( 1=>"Sun", 2=>"Mon", 3=>"Tue", 4=>"Wed", 5=>"Thu", 6=>"Fri", 7=>"Sat" );
$ThisMonthTS = strtotime( date("Y-m-01", $tsInMonth ) );
$NextMonthTS = strtotime( date("Y-m-01", strtotime("next month", $tsInMonth) ) );
$weekDates = array();
for($Ord=1;$Ord<=5;$Ord++){
$DateOfInterest = (-1 == $Ord)
? strtotime( "last ".$Names[$day], $NextMonthTS )
: strtotime( $Names[$day]." + ".($Ord-1)." weeks", $ThisMonthTS );
($Ord==5 && (int)date("m",$DateOfInterest)==(int)date("m",$NextMonthTS))
? false
: $weekDates [] = $DateOfInterest;
}
return $weekDates;
}
///// Usage /////
foreach (getWeekDates("2010", "2", "2") as $day) {
echo "
" . date("l, Y-m-d", $day);
}
///// End of code /////
I hope it helps someone.