Tom
Tom

Reputation: 34376

work out the date of the fourth saturday in the current month

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

Upvotes: 5

Views: 2696

Answers (6)

Robin Day
Robin Day

Reputation: 102578

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 the strtotime docs.

EDIT:

Just to make the answer complete, thanks to Tom and Paul Dixon

date('dS F',strtotime('Fourth Saturday '.date('F o'))); 

Upvotes: 7

Paul Dixon
Paul Dixon

Reputation: 301135

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 :)

Upvotes: 7

kmkaplan
kmkaplan

Reputation: 18970

function fourth_saturday($year, $month)
{
    $info = localtime(mktime(0, 0, 0, $month , 1, $year));
    return 28 - $info[6];
}

Upvotes: 0

ShuggyCoUk
ShuggyCoUk

Reputation: 36486

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

Upvotes: -1

Elie
Elie

Reputation: 13875

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).

Upvotes: 3

Devin Jeanpierre
Devin Jeanpierre

Reputation: 95626

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.

Upvotes: 2

Related Questions