PHP Logo

PHP: Find number of weeks in a given month

Posted by

The following function finds the number of weeks in a given month, assuming Monday as the first day of the week.

<?php
function weeks_in_month($month, $year) {
 // Start of month
 $start = mktime(0, 0, 0, $month, 1, $year);
 // End of month
 $end = mktime(0, 0, 0, $month, date('t', $start), $year);
 // Start week
 $start_week = date('W', $start);
 // End week
 $end_week = date('W', $end);

 if ($end_week < $start_week) { // Month wraps
   return ((52 + $end_week) - $start_week) + 1;
 }

 return ($end_week - $start_week) + 1;
}

 

3 comments

  1. Hi,
    I made a little fix to this function. Here is the code.

    Code block    
    function weeks_in_month($month, $year) {
     // Start of month
     $start = mktime(0, 0, 0, $month, 1, $year);
     // End of month
     $end = mktime(0, 0, 0, $month, date('t', $start), $year);
     // Start week
     $start_week = date('W', $start);
     // End week
     $end_week = date('W', $end);
     
     if ($end_week < $start_week) { // Month wraps
                //year has 52 weeks
                $weeksInYear = 52;
                //but if leap year, it has 53 weeks
                if($year % 4 == 0) {
                    $weeksInYear = 53;
                }
                return (($weeksInYear + $end_week) - $start_week) + 1;
            }
     
     return ($end_week - $start_week) + 1;
    }

    My code includes leap year in calculations.

    Best Regards,
    Emil Jaszczuk

Leave a Reply to Emil Jaszczuk Cancel reply

Your email address will not be published. Required fields are marked *