Bit stuck about how to go about this one. Given the current month, I need to to return the date of the fourth saturday of each month.
e.g. This month would be Feb 20th, next would be March 27th.
Thanks
Bit stuck about how to go about this one. Given the current month, I need to to return the date of the fourth saturday of each month.
e.g. This month would be Feb 20th, next would be March 27th.
Thanks
Find the first Saturday of the month, and then add three weeks to that.
If you don't know when the first Saturday is (or, rather, don't know specifically a date corresponding with a day name), you might want to look at the Doomsday algorithm, which I conveniently looked at for another post with a somewhat similar issue.
The earliest date for the fourth Saturday is the 22nd of the month. So look at the 22nd, see what day of the week it is, if it's not Saturday, add one day to the date, and check again, until you find a match (maximum you would have to check is 6 days).
in PHP rather than pseudo code (think requires 5.2)
$date = getdate();
$date-> setDate($date->format('Y'), $date->format('Y'), '1'); // 1st of month.
while ($date->format('w' != 6)
$date->modify("+1 day");
$date->modify("+21 day"); // date is now on the fourth saturday
I'm not a PHP coder, however, it seems strtotime is what you're after.
You can use strtotime("fourth Saturday") and it will return the 4th saturday.
Check out http://uk2.php.net/strtotime
EDIT:
Just to make the answer complete, thanks to Tom and Paul Dixon
date('dS F',strtotime('Fourth Saturday '.date('F o')));
You can use strtotime to find "next saturday" based on a starting date. If that starting date is the day before the earliest possible preceding day (21st) we get the answer...
//required year/month
$yyyymm="2009-01";
//find next saturday after earliest possible date
$t=strtotime("next saturday", strtotime("{$yyyymm}-21"));
//here you go!
echo "4th saturday of $yyyymm is ".strftime("%Y-%m-%d",$t)."\n";
Earliest possible 4th repeat of a day in any month is the 22nd (1,8,15,22), last possible 4th repeat is 28th (7,14,21,28).
EDIT: Although it's not clear in the documentation, you can request the "fourth saturday" too - use the zeroth day of the month as the basis:
$t=strtotime("fourth saturday", strtotime("{$yyyymm}-00"));
or omit the basis time and specify the month and year directly:
$t=strtotime("fourth saturday feb 2009");
Tip of the hat to Robin "I'm not a PHP coder" Day for spotting that :)
function fourth_saturday($year, $month)
{
$info = localtime(mktime(0, 0, 0, $month , 1, $year));
return 28 - $info[6];
}