PHP Date custom script help needed
I have to get开发者_运维知识库 how many Saturdays and how many Sundays in a given month and pass it to for loop. My input can be like this
HowmanySaturdays("Feb,2010");
or
HowmanySaturdays("02,2010");
Brute force method: Iterate over all days of the given month; for any day that is a saturday, increase a counter variable. When done looping, return the counter.
Better method: Find the first saturday in the given month, then increase by 7 until you hit the next month.
Yet better method: find day-of-week of the first day in the given month. If it's not a saturday, increase by the required number of days to reach a saturday. Then proceed using method 2.
Even better: Find the first saturday using method 2. Find the number of days in the month. These two give you the remaining number of days in the month. Divide by 7 and round down.
function HowManySaturdays($month)
{
$date = explode(',', $month);
$date = date_parse($date[1] . '-' . $date[0]);
$days = cal_days_in_month(CAL_GREGORIAN, $date['month'], $date['year']);
$timestamp = jdtounix(gregoriantojd($date['month'], 1, $date['year']));
$date = getdate($timestamp);
return (floor($days/7)) + ((($days % 7) + $date['wday'] >=7) ? 1 : 0);
}
function HowManyDays($day,$month,$year)
{
$d = date("t", mktime(0,0,0,$month,1,$year));
$n = 1;
$noOfDays = array();
echo "<b>".$day."'s </b> found in $month,$year <br>";
for ($i = 1; $i <= $d; $i++) {
$c = date("l", mktime(0,0,0,$month,$i,$year));
if (strtolower($c) == strtolower($day)) {
$noOfDays[$n] = $i."/".$month."/".$year;
echo "<b>".$c." On ".$i."/".$month."/".$year."</b><br>";
$n++;
} else {
//echo $c." On ".$i."/".$month."/".$year."<br>";
}
}
return $noOfDays;
}
$noOfDays = HowManyDays("Saturday",1,2010);
print_r($noOfDays);
This will return days and its date of the month as a array.
精彩评论