tags:

views:

46

answers:

3

I am trying to build a php function that would return an array with the start date and end date of the last n number of weeks. this would include the current week. It would look something like this:

function lastnweeks(n)
{
//the code. I am not asking for the code itself but ideas on how to accomplish this
return $array; 
}
$lastnweeks =lastnweeks(2);
print_r($lastnweeks);

this would print:

Array ( 
    [0] =>  Array ( 
        [0] => 2010/09/20 
        [1] => 2010/09/26
   )[1] => Array ( 
        [0] => 2010/09/13 
        [1] => 2010/09/19
))
A: 

Use strtotime to get the monday and then subtract the number of seconds for each week:

function lastnweeks($n) {
    $time = strtotime('Monday 00:00:00+0000');
    $arr = array();
    while ($n-- > 0) {
        $arr[] = array_reverse(array(
            date('Y/m/d', $time-=86400),   // sunday
            date('Y/m/d', $time-=6*86400)  // monday
        ));
    }
    return $arr;
}

array_reverse is used to reverse the array as the calculation walks backwards.

Gumbo
Thanks, this is very helpful
El Fuser
A: 

Take your pick

$last_week = strtotime('last Week');
echo "Last Week ".date("Y/m/d", $last_week)."<br />\n";

or

$last_week = mktime(0,0,0,date("m"),date("d")-7,date("Y"));
echo "Last Week ".date("Y/m/d", $last_week)."<br />\n";
Phill Pafford
+1  A: 

I wouldn't use an absolute number of seconds because of daylight savings time and leapyears/leapseconds. You can let PHP's strtotime() function take care of this for you by using relative dates. Each iteration through a loop you can simply tell the function to find "Last Monday", and then use that result as your starting point for the next iteration.

The code:

$past_weeks = 7;
$relative_time = time();
$weeks = array();

for($week_count=0;$week_count<$past_weeks;$week_count++) {
    $monday = strtotime("last Monday", $relative_time);
    $sunday = strtotime("Sunday", $monday);
    $weeks[] = array(
        date("Y-m-d", $monday),
        date("Y-m-d", $sunday),
    );
    $relative_time = $monday;
}

var_dump($weeks);

The output:

array
  0 => 
    array
      0 => string '2010-09-20' (length=10)
      1 => string '2010-09-26' (length=10)
  1 => 
    array
      0 => string '2010-09-13' (length=10)
      1 => string '2010-09-19' (length=10)
  2 => 
    array
      0 => string '2010-09-06' (length=10)
      1 => string '2010-09-12' (length=10)
  3 => 
    array
      0 => string '2010-08-30' (length=10)
      1 => string '2010-09-05' (length=10)
  4 => 
    array
      0 => string '2010-08-23' (length=10)
      1 => string '2010-08-29' (length=10)
  5 => 
    array
      0 => string '2010-08-16' (length=10)
      1 => string '2010-08-22' (length=10)
  6 => 
    array
      0 => string '2010-08-09' (length=10)
      1 => string '2010-08-15' (length=10)
Jeff Standen