Only Show Saturdays of the month

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
xionhack
Forum Contributor
Posts: 100
Joined: Mon Nov 10, 2008 9:22 pm

Only Show Saturdays of the month

Post by xionhack »

Hello. I want to show all the saturdays of this month, I tried the following code but its not working, can somebody help me?

Code: Select all


$dtFirstDay = date("j/n/Y", mktime(0, 0, 0, date("m") , date("d")-date("d")+1, date("Y")));

$dtLastDay = date("j/n/Y", mktime(0, 0, 0, date("m")+1 , date("d")-date("d"), date("Y"))); 

    for($date = $dbFirstDay ; $date < $dtLastDay; $date = mktime(0,0,0,date("m", $date),date("d", $date)+1,date("Y", $date))){
        if(date('w' ,$date) == 0){
            echo $date;
        }

        }

User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Only Show Saturdays of the month

Post by Christopher »

You can use this logic to find all the Saturdays:

Code: Select all

function first_weekday_of_month($day_of_week, $month='', $year='') {
	// use current date of not specified
	if ($month == '') {
		$month = date('n');
	}
	if ($year == '') {
		$year = date('Y');
	}
	$seconds_in_day = 60 * 60 * 24;
	// get timestamp for the 1st
	$ts = strtotime("$month/1/$year 12:00");
	// loop through days until matching day of week is found
	while (date('l', $ts) != $day_of_week) {
		$ts += $seconds_in_day;
	}
	return $ts;
}

$day_of_week = 'Saturday';

$ts = first_weekday_of_month($day_of_week);
echo "First $day_of_week is " . date('m/d/Y', $ts) . "<br/>";

$ts = first_weekday_of_month($day_of_week, 6, 2010);
echo "First $day_of_week is " . date('m/d/Y', $ts) . "<br/>";
(#10850)
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: Only Show Saturdays of the month

Post by AbraCadaver »

Seems to be a popular homework assignment. Anyway, here's a quick stab at it. It could be cleaned up / shortened:

Code: Select all

$date = strtotime(date('m/01/Y') . ' -1 day');
$month = date('n', $date) + 1;

while($date = strtotime('next Saturday', $date)) {
	if(date('n', $date) == $month) {
		$saturdays[] = $date;
	} else {
		break;
	}
}
You can put it in a function and pass in the day like Christopher shows.
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
xionhack
Forum Contributor
Posts: 100
Joined: Mon Nov 10, 2008 9:22 pm

Re: Only Show Saturdays of the month

Post by xionhack »

Thanks! one question, how would u modify this to show every saturday and tuesday of the month?! thanks!
Post Reply