Happy Codings - Programming Code Examples
Html Css Web Design Sample Codes CPlusPlus Programming Sample Codes JavaScript Programming Sample Codes C Programming Sample Codes CSharp Programming Sample Codes Java Programming Sample Codes Php Programming Sample Codes Visual Basic Programming Sample Codes


Php Programming Code Examples

Php > Databases Code Examples

Count how many weeks in the month have a specified day

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
Count how many weeks in the month have a specified day <? // // count how many weeks in the month have a specified day, such as Monday. // we know there will be 4 or 5, so no need to check for $weeks<4 or $weeks>5 // // Initial formula doesn't work well, so I "reversed-engineered" to get the formula. // 0 - Sunday,...,6 - Saturday for ($year = 2001; $year <= 2037; $year++) { for ($month = 1; $month <= 12; $month++) { $num_of_days = date("t", mktime(0,0,0,$month,1,$year)); echo "<HR> Month=$month Year=$year <BR>"; echo "Number of days = $num_of_days <BR>"; $firstdayname = date("D", mktime(0, 0, 0, $month, 1, $year)); $firstday = date("w", mktime(0, 0, 0, $month, 1, $year)); $lastday = date("t", mktime(0, 0, 0, $month, 1, $year)); echo "First day of the month = $firstday,$firstdayname <BR> "; for ($day_of_week = 0; $day_of_week <= 6; $day_of_week++) { if ($firstday > $day_of_week) { // means we need to jump to the second week to find the first $day_of_week $d = (7 - ($firstday - $day_of_week)) + 1; } elseif ($firstday < $day_of_week) { // correct week, now move forward to specified day $d = ($day_of_week - $firstday + 1); } else { // my "reversed-engineered" formula if ($lastday==28) // max of 4 occurences each in the month of February with 28 days $d = ($firstday + 4); elseif ($firstday==4) $d = ($firstday - 2); elseif ($firstday==5 ) $d = ($firstday - 3); elseif ($firstday==6) $d = ($firstday - 4); else $d = ($firstday - 1); if ($lastday==29) // only 1 set of 5 occurences each in the month of February with 29 days $d -= 1; } $d += 28; // jump to the 5th week and see if the day exists if ($d > $lastday) { $weeks = 4; } else { $weeks = 5; } if ($day_of_week==0) echo "Sun "; elseif ($day_of_week==1) echo "Mon "; elseif ($day_of_week==2) echo "Tue "; elseif ($day_of_week==3) echo "Wed "; elseif ($day_of_week==4) echo "Thu "; elseif ($day_of_week==5) echo "Fri "; else echo "Sat "; echo "occurences = $weeks <BR> "; } // for $day_of_week loop } // for $mth loop } // for $year loop ?>