計算一周中的天數
當給定週數時,例如從日期-u %W 獲得的,我們可能需要計算該週內的天數(從星期一開始)。這使我們能夠產生該週內的特定日期清單。
PHP 實作
在PHP 中,我們可以利用循環來產生日期:
<code class="php">$week_number = 40; $year = 2008; for ($day = 1; $day <= 7; $day++) { echo date('m/d/Y', strtotime($year . "W" . $week_number . $day)) . "\n"; }
輸出:
10/06/2008 10/07/2008 10/08/2008 10/09/2008 10/10/2008 10/11/2008 10/12/2008
輸出:
輸出:<code class="php">function week_from_monday($date) { // Assuming $date is in format DD-MM-YYYY list($day, $month, $year) = explode("-", $date); // Get the weekday of the given date $wkday = date('l', mktime(0, 0, 0, $month, $day, $year)); switch ($wkday) { case 'Monday': $numDaysToMon = 0; break; case 'Tuesday': $numDaysToMon = 1; break; case 'Wednesday': $numDaysToMon = 2; break; case 'Thursday': $numDaysToMon = 3; break; case 'Friday': $numDaysToMon = 4; break; case 'Saturday': $numDaysToMon = 5; break; case 'Sunday': $numDaysToMon = 6; break; } // Timestamp of the Monday for that week $monday = mktime(0, 0, 0, $month, $day - $numDaysToMon, $year); $seconds_in_a_day = 86400; // Get date for 7 days from Monday (inclusive) for ($i = 0; $i < 7; $i++) { $dates[$i] = date('Y-m-d', $monday + ($seconds_in_a_day * $i)); } return $dates; }
Array ( [0] => 2008-10-06 [1] => 2008-10-07 [2] => 2008-10-08 [3] => 2008-10-09 [4] => 2008-10-10 [5] => 2008-10-11 [6] => 2008-10-12 )</code>輸出:輸出:輸出:從給定日期取得日期另一種方法是取得給定特定日期的特定週的日期。例如,要取得包含 2008 年 10 月 7 日的一週日期:輸出:
以上是如何在給定週數或特定日期的 PHP 中計算一週中的天數?的詳細內容。更多資訊請關注PHP中文網其他相關文章!