Given a week number, e.g. date -u +%W
, how do you calculate the days in that week starting from Monday?
Example rfc-3339 output for week 40:
2008-10-06 2008-10-07 2008-10-08 2008-10-09 2008-10-10 2008-10-11 2008-10-12
#2 – Calculate the Number of Weeks Between Dates To determine how many weeks elapsed between two dates, we can use a simple formula to find the number of days between the dates, then divide by 7.
PHP
$week_number = 40; $year = 2008; for($day=1; $day<=7; $day++) { echo date('m/d/Y', strtotime($year."W".$week_number.$day))."\n"; }
In PHP, adapted from this post on the PHP date manual page:
function week_from_monday($date) { // Assuming $date is in format DD-MM-YYYY list($day, $month, $year) = explode("-", $_REQUEST["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; }
Output from week_from_monday('07-10-2008')
gives:
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 )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With