Get first/second/thrid weekend day of a specific month in PHP

I'm trying to find a way to get the first/second/thrid/fourth/last weekend day of a specific month in PHP.

I know I can do this for weekdays using strtotime('first weekday', mktime(0, 0, 0, 5, 1, 2009)) but I need a solution to do the same for weekend days.

For example the first weekend day in May is the Saturday  2nd. The second weekend day in May is Sunday the 3rd. The third weekend day in May is Saturday 9th etc.

Can anyone provide a way to do this to produce the above results?
LVL 3
cameroncookeAsked:
Who is Participating?
 
Ray PaseurCommented:
Another way to look at this problem.

Best regards, ~Ray
<?php // RAY_weekends.php
error_reporting(E_ALL);
echo "<pre>\n";
 
 
// FIND ALL THE WEEKEND DAYS IN MAY, 2009
 
// ISO8601 DATE TO START
$start = '2009-05-01';
 
// FIND THE LAST DAY OF THE MONTH
$end   = date('Y-m', strtotime($start)) . '-' . date('t', strtotime($start));
 
// FIND ALL THE WEEKEND DAYS BY ITERATION
$weekend_days = array();
$working      = TRUE;
$now          = strtotime($start);
 
while ($working)
{
   $day = date('D Y-m-d', $now);
   if (substr($day,0,1) == 'S')
   {
      $weekend_days[] = $day;
   }
   $now = $now + 60*60*24;
   $chk = date('Y-m', $now);
   if ($chk > $end) $working = FALSE;
}
var_dump($weekend_days);

Open in new window

0
 
Ray PaseurCommented:
strtotime('first saturday') will work.  I will post some example code for you in a moment.  Best, ~Ray
0
 
Ray PaseurCommented:

<?php // RAY_weekends.php
error_reporting(E_ALL);
echo "<pre>\n";
 
// FIRST DAY OF THIS MONTH
$start = date('Y-m') . '-01';
 
// WEEKENDS
$w1 = date('Y-m-d D', strtotime($start . ' first Saturday'));
$w2 = date('Y-m-d D', strtotime($start . ' second Saturday'));
$w3 = date('Y-m-d D', strtotime($start . ' third Saturday'));
 
var_dump($w1);
var_dump($w2);
var_dump($w3);

Open in new window

0
 
cameroncookeAuthor Commented:
Fantasic. Great solution. Very clear and easy to understand. Did exactly what I needed. Many thanks.
0
 
Ray PaseurCommented:
Thanks for the points!  Functions strtotime() and date() work together in ways that are almost magical.  Sidebar note - always use the ISO8601 format for dates in your internal representations.  It works well in PHP and MySQL and you can always use the date() function to format "pretty" dates for human-readable displays.

Best regards, ~Ray
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.