Page 1 of 1

how to accomplish this ?

Posted: Thu Apr 03, 2008 4:25 am
by PHPycho
Hello forums!!
Suppose consider the following case:
I had the following date range:
From: 2006-05-10
To: 2007-08-15
Q's?
1> How to find the no of saturdays within the range with appropriate date format ie YYYY-mm-dd .

2> How to find the first and last saturday of each month within the range ?

Thanks in advance for the kind help.

Re: how to accomplish this ?

Posted: Thu Apr 03, 2008 10:25 am
by Jonah Bron
Well, if you can figure out how to loop through every date in that range, you can use this to find out if it is a Sunday:

Code: Select all

$day = getdate(strtotime('2006-05-10'));
$day = $day['weekday'];
[/size]

Re: how to accomplish this ?

Posted: Fri Apr 04, 2008 1:03 am
by PHPycho
I got the solution;Here it goes:

Code: Select all

 
<?php
// convert to timestamp
$start = strtotime( '2006-05-10 00:00:00');
$end = strtotime( '2007-08-15 00:00:00');
 
// initialize an array to hold the saturdays
$saturdays = array();
$monthSaturdays = array();
 
// this is for question 1
for ( $i = $start; $i  <= $end; $i += 86400 ) {
   if ( (int)date( 'w', $i ) == 6 ) {
        // store the saturdays
        $saturdays[] = date( 'Y-m-d', $i );
    }
}
 
// this is for question 2
for ( $i = $start; $i <= $end; $i += 86400 ) {
    $currentMonth = date( 'Y-m', $i );
    if ( ! isset( $monthSaturdays[$currentMonth] ) ) {
        $monthSaturdays[$currentMonth] = array( null, null );
    }
    // store the first Saturday of the month (index 0 will hold the firs, index 1 will hold the last)
    if ( ! isset( $monthSaturdays[$currentMonth][0] ) && (int)date( 'w', $i ) == 6 ) {
        $monthSaturdays[$currentMonth][0] = date( 'Y-m-d', $i );   
    }
    // the last Saturday will be automatically set
    if ( (int)date( 'w', $i ) == 6 ) {
        $monthSaturdays[$currentMonth][1] = date( 'Y-m-d', $i ); 
    }
}
 
?>