0

我正在寻找日期在一个月的哪一周开始,一周从星期五开始。例如,日历看起来像这样:

Week count   F   Sa  Su  M   Tu  W   Th
----------------------------------------
       0         1   2   3   4   5   6
       1     7   8   9   10  11  12  13
       2     14  15  16  17  18  19  20
       3     ...

输入将是时间戳格式 ( $currentDate) 的日期,我正在寻找$weekCount.

谢谢

4

1 回答 1

1

只需要一次返回 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.

于 2012-09-27T12:44:20.077 回答