antonyjohn Posted September 10, 2007 Share Posted September 10, 2007 Is there any function to count the no.of saturadays and sundays in a given month of an year? Quote Link to comment https://forums.phpfreaks.com/topic/68662-calendar-function/ Share on other sites More sharing options...
Wuhtzu Posted September 10, 2007 Share Posted September 10, 2007 I don't think there is a function which does what you want but it can "easily" be created. All you basically need to do is loop over all the days in a given month and check if they are a saturday or a sunday. This is how I would do it: <?php function count_sat_sun($timestamp,$count_to_return) { //Seperate day, month and year $day = date('d', $timestamp); $month = date('m', $timestamp); $year = date('Y', $timestamp); //Calculate the number of days in month $days_in_month = cal_days_in_month(CAL_GREGORIAN, $month, $year); //Set some counters $day_num = 1; $num_of_sat = 0; $num_of_sun = 0; //Loop over the days while($day_num <= $days_in_month) { $day_timestamp = mktime(0, 0, 0, $month, $day_num, $year); $day_of_week = date('w', $day_timestamp); //Add to the saturday count if the day is a saturday if($day_of_week == 6) { $num_of_sat++; } //Add to the sunday count if the day is a sunday if($day_of_week == 0) { $num_of_sun++; } $day_num++; } //Determine the return value based on function argument if($count_to_return == 'sat') { return $num_of_sat; } elseif($count_to_return == 'sun') { return $num_of_sun; } } ?> <?php //How to use the function: //Return the num of saturdays in todays month count_sat_sun(time(),'sat') //Return the num of sundays in todays month count_sat_sun(time(),'sun') ?> Redefine the function with whatever arguments you think are more logic than mine. You could make separate functions for each day or change the $timestamp argument to be a $month and $year argument. It's up to you. This is what I found somewhat logic Btw. can anyone see a smarter way to do this? If you know the number of days in the month, the starting day (mon-sat) and the ending day (mon-sat) you should be able to do some basic "calendar math" or "calendar logic" but I couldn't comprehend it and didn't know if it would be faster and simpler. Quote Link to comment https://forums.phpfreaks.com/topic/68662-calendar-function/#findComment-345433 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.