How to count number of weeks and days of week any month
How to count 开发者_Go百科number of weeks and days of week any month.
Ok, I think I got you:
$days = cal_days_in_month(CAL_GREGORIAN, 1, 2011);
$week_day = date("N", mktime(0,0,0,1,1,2011));
$weeks = ceil(($days + $week_day) / 7);
echo $weeks;
This code returns the number of days, weeks of a month.
<?php
for ($year = 2011; $year <= 2012; $year++){
for ($month = 1; $month <= 12; $month++){
$num_of_days = date("t", mktime(0,0,0,$month,1,$year));
$month_Year = date("F",mktime(0, 0, 0, $month, 1, $year));
echo "<b>$month_Year, $year </b><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));
$lastdayname = date("D", mktime(0, 0, 0, $month, $lastday, $year));
echo "First day of the month = $firstday,$firstdayname <BR> ";
echo "Last day of the month = $lastday,$lastdayname <BR> ";
$no_of_weeks = 1;
$count_weeks = 0;
while($no_of_weeks <= ($lastday+$firstday)){
$no_of_weeks += 7;
$count_weeks++;
}
echo "Number Of weeks = $count_weeks <br><br>";
}
}
?>
It depends on "what is the starting day of a week?"
Let's say our first day of a week is Monday, means if there are 5 Mondays in a month, we will have a month with 5 weeks.
function nbweeks_of_month($month, $year){
$nb_days = cal_days_in_month(CAL_GREGORIAN, $month, $year);
$first_day = date('w', mktime(0, 0, 0, $month, 1, $year));
if($first_day > 1 && $first_day < 6){
// month started on Tuesday-Friday, no chance of having 5 weeks
return 4;
} else if($nb_days == 31) return 5;
else if($nb_days == 30) return ($first_day == 0 || $first_day == 1)? 5:4;
else if($nb_days == 29) return $first_day == 1? 5:4;
}
<?php
function weeks($month, $year){
$num_of_days = date("t", mktime(0,0,0,$month,1,$year));
$lastday = date("t", mktime(0, 0, 0, $month, 1, $year));
$no_of_weeks = 0;
$count_weeks = 0;
while($no_of_weeks < $lastday){
$no_of_weeks += 7;
$count_weeks++;
}
return $count_weeks;
}
echo weeks(2,2011)."<br/>";
echo weeks(9,2012)."<br/>";
?>
精彩评论