Calculating days of week given a week number
This calculation varies largely depending on where you live. For example, in Europe we start the week with a Monday, in US Sunday is the first day of the week. In UK week 1 is on Jan 1, others countries start week 1 on the week containing the first Thursday of the year.
You can find more general information at http://en.wikipedia.org/wiki/Week#Week_number
If you've got Zend Framework you can use the Zend_Date class to do this:
require_once 'Zend/Date.php';
$date = new Zend_Date();
$date->setYear(2008)
->setWeek(40)
->setWeekDay(1);
$weekDates = array();
for ($day = 1; $day <= 7; $day++) {
if ($day == 1) {
// we're already at day 1
}
else {
// get the next day in the week
$date->addDay(1);
}
$weekDates[] = date('Y-m-d', $date->getTimestamp());
}
echo '<pre>';
print_r($weekDates);
echo '</pre>';
Since this question and the accepted answer were posted the DateTime classes make this much simpler to do:-
function daysInWeek($weekNum)
{
$result = array();
$datetime = new DateTime('00:00:00');
$datetime->setISODate((int)$datetime->format('o'), $weekNum, 1);
$interval = new DateInterval('P1D');
$week = new DatePeriod($datetime, $interval, 6);
foreach($week as $day){
$result[] = $day->format('D d m Y H:i:s');
}
return $result;
}
var_dump(daysInWeek(24));
This has the added advantage of taking care of leap years etc..
See it working. Including the difficult weeks 1 and 53.
PHP
$week_number = 40;
$year = 2008;
for($day=1; $day<=7; $day++)
{
echo date('m/d/Y', strtotime($year."W".$week_number.$day))."\n";
}
Below post was because I was an idiot who didn't read the question properly, but will get the dates in a week starting from Monday, given the date, not the week number..
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
)