niiyz
5/10/2013 - 1:14 AM

カレンダー作成などで一ヶ月に何週間あるか調べる関数。

カレンダー作成などで一ヶ月に何週間あるか調べる関数。

<?php
    # What week are either in the one month
    function get_week_cnt($year, $month) {
        $firstDay    = mktime(0, 0, 0, $month, 1, $year);    // Month first day
        $lastDay    = mktime(0, 0, 0, $month+1, 0, $year);    // End of day
        
        $ddd = $firstDay;                // loop 
        $startWeek = date('w', $ddd);    // Start day of the week
        # Loop until the end of days from the first day of month
        while ($lastDay > $ddd) {
            # Count the day of the week the same as the start day of the week
            if (date('w', $ddd) == $startWeek) {
                ++ $weekCnt;
            }
            # I go the 1st
            $ddd += 24 * 60 * 60;
        }
        # UP count the last day of the week if less than the start day of the week
        if (date('w', $ddd) < $startWeek) {
            ++ $weekCnt;
        }

        return $weekCnt;
    }