The following PHP function returns the n-th weekday of a month, e.g. the 3rd Wednesday in January 2012 in the form 18-1-2012:
<?php
function giveNthDay($month, $year, $no, $day) {
$counter = 0;
for($i=1;$i<=31;$i++) { //Schleife für 31 Tage
if(!checkdate($month, $i, $year)) { //wenn datum nicht existiert (bspw. 30. februar) zu nächstem schleifendurchlauf springen
continue;
} else {
if(date('l', strtotime($i.'-'.$month.'-'.$year))==$day) { //wenn generiertes Datum gleicher Wochentag wie gesuchter Tag $day
$counter++; //dann $counter um eins erhöhen
if($counter==$no) { //falls $counter==$no, also falls bspw. DRITTER ($no==$counter==3) Mittwoch gefunden, Datum zurückgeben
return $i.'-'.$month.'-'.$year;
}
}
}
}
return false; //existiert nicht, bspw. fünfter Sonntag gibt es nicht in jedem Monat
}
?>
If the date doesn't exist (e.g. 5th Friday in January 2012), it returns false.
This works fine for examples like:
giveNthDay(1, 2012, 3, "Wednesday");
giveNthDay(1, 2020, 3, "Wednesday");
giveNthDay(1, 2031, 3, "Wednesday");
but from
giveNthDay(1, 2038, 3, "Wednesday");
on, it returns false even though every January has more than 3 Wednesdays!
I tried hard to find out what the reason for this strange behaviour is but I can't figure it out. Can anyone help me?
getdate()function?