2012-09-27 118 views
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形式輸出的日期。

感謝

回答

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); 

這段代碼沒有說明如果我們說的是週五30日,那麼實際上我們是在下個月的第0周?如果需要的話,從開篇文章可以看不清楚。

+0

太好了,謝謝! – Ollie

相關問題