Find an array of dates

Let $wk=48, $year=2011, where $wkis the week of the year. Then

$days=array("2011-11-28","2011-11-29","2011-11-30","2011-12-01",
"2011-12-02","2011-12-03","2011-12-04");

Is there any way to find this array (7 days, from to ) if only $wkand $year?


Answer 1, authority 100%

Some difficult decisions you have 🙂

echo date("Y-m-d", strtotime("+48 weeks", strtotime("2011-01-01 00:00:00")));

and a loop to get the week.

OK, for Monday:

$t = strtotime("+48 weeks", strtotime("2011-01-01 00:00:00"));
$monday = strtotime('this monday', $t);
if ($monday > $t) {
    $monday = strtotime('last monday', $t);
}
echo date('D Y-m-d', $monday)."\n";

Your arguments ? 🙂


Answer 2, authority 100%

$wk = 48;
$year = 2011;
$date = new DateTime($year . '-01-01');
$date->add(new DateInterval('P' . $wk . 'W'));
$day = $wk*7 - $date->format('w') + 1;
$date = new DateTime($year . '-01-01');
$date->add(new DateInterval('P' . $day . 'D'));
for($i = 0; $i < 7; ++$i){
    echo $date->format('Y-m-d'), '<br>';
    $date->add(new DateInterval('P1D'));
}

But only the DateTime object has been around since php 5.3.0.


Answer 3, authority 50%

$weekNumber = 48;
$year = 2011;
//86400
$beginYear = mktime(0, 0, 0, 1, 1, $year);
for ($i = 1; $i <= 365; $i++)
{
    $days[] = date('Y-m-d', $beginYear);
    $beginYear += 86400;
}
$beginWeek = (($weekNumber - 1) * 7 + 2);
for ($i = $beginWeek; $i < $beginWeek + 7; $i++)
{
    echo $days[$i] . '<br>';
}

PS. leap year is not taken into account.