只需要一次返回 7 天来计算上周五的数量,直到你发现你已经涵盖了所有这些。
循环将始终超出第一个星期五,以涵盖星期五不是本月第一天的正常情况。如果星期五是该月的第一天,那么您需要减少增量以解决超调。
$currentDate = time(); // e.g.
$dayOfMonth = date('j', $currentDate);
$ym = date('Y-m', $currentDate);
$firstFriday = strtotime("Friday ".$ym);
$dateOfFirstFriday = date('j', $firstFriday);
// we need to reduce count by 1 if friday is the 1st, to compensate
// for overshooting by a week due to the >= in the while loop
$weekCount = ($dateOfFirstFriday == 1) ? -1 : 0;
while ($dayOfMonth >= $dateOfFirstFriday) {
$weekCount ++;
$dayOfMonth = $dayOfMonth - 7;
}
var_dump($weekCount);
This code doesn't account for if we are on say Fri 30th, then actually are we in week 0 of the next month? Not clear though from opening post if that is required.