Forum Moderators: coopster
2> How to find the first and last saturday of each month within the range ?
Thanks in advance for the kind help.
$start_ts = strtotime($start); // start time stamp
$end_ts = strtotime($end); // end time stamp
$day_sec = 86400;
$interval = ($end_ts - $start_ts)/$day_sec; // number of days
echo "There are $interval days<br />\n";
$count = 0;
$working_ts = $start_ts;
while ($working_ts < $end_ts) { // loop through each day to find saturdays
$day = date('w', $working_ts);
if ($day == 6) { // this is a saturday
$count++;
}
$working_ts = $working_ts + $day_sec;
}
echo "There are $count Saturdays in that interval<br />\n";
Note: The valid range of a timestamp is typically from Fri, 13 Dec 1901 20:45:54 GMT to Tue, 19 Jan 2038 03:14:07 GMT. (These are the dates that correspond to the minimum and maximum values for a 32-bit signed integer.) Additionally, not all platforms support negative timestamps, therefore your date range may be limited to no earlier than the Unix epoch. This means that e.g. dates prior to Jan 1, 1970 will not work on Windows, some Linux distributions, and a few other operating systems. PHP 5.1.0 and newer versions overcome this limitation though.
So in PHP >= 5.1.0 the negative timestamps should not be an issue, but any dates outside of the year range shown (1901 - 2038) are going to give you issues. I have found the PHP Calendar Functions [php.net] come in handy for doing date math. In the past I can recall others needed more accuracy regarding the time associated with the date so they used a different approach [webmasterworld.com]. Here is another option anyway, using the Calendar functions.
$day = 6; // 0=Sun, 1=Mon, ... 6=Sat
$beg = '2006-05-10';
$end = '2007-08-15';
$days = 0; // initialize
list($yyyy, $mm, $dd) = explode('-', $beg);
$begJul = gregoriantojd($mm, $dd, $yyyy);
list($yyyy, $mm, $dd) = explode('-', $end);
$endJul = gregoriantojd($mm, $dd, $yyyy);
$daysPassed = $endJul - $begJul;
$days = floor(($daysPassed) / 7);
/**
* If the beginning date or the ending date (or both) happen to be the day
* we are monitoring, add 1 to the day count to correct our division math:
*/
if (jddayofweek($begJul) == $day ¦¦ jddayofweek($endJul) == $day) {
$days++;
}
print "There were $daysPassed days passed and $days Saturdays.";
If you need the first and last Saturday for each and every month in the time period you can use some of the same functions. Just wrap them in different logical control structures.
Note: I only ran some quick tests on that code so you will want to test it more extensively if you use it.