8

Can anybody tell how to display all the week numbers that are covered between two dates in PHP.The dates may be of different year.

IF i am using start date as "2011-09-16" and end date as "2011-09-21" it will show me week 37 and 38.

Sitansu
  • 861
  • 2
  • 14
  • 24
  • 2
    Have you tried anything so far? – Bojangles Sep 21 '11 at 07:19
  • 1
    *(reference)* http://php.net/manual/en/class.dateperiod.php – Gordon Sep 21 '11 at 07:28
  • 2
    This question is marked as a duplicate. I don't think the questions are duplicates since this question focus on week numbers whereas [the other](http://stackoverflow.com/questions/2736784/how-to-find-the-dates-between-two-specified-date) focus on dates within a period. – Kristoffer Bohmann Dec 28 '15 at 17:41

3 Answers3

13

You could use something like this...

$startTime = strtotime('2011-12-12');
$endTime = strtotime('2012-02-01');

$weeks = array();

while ($startTime < $endTime) {  
    $weeks[] = date('W', $startTime); 
    $startTime += strtotime('+1 week', 0);
}

var_dump($weeks);

CodePad.

Output

array(8) {
  [0]=>
  string(2) "50"
  [1]=>
  string(2) "51"
  [2]=>
  string(2) "52"
  [3]=>
  string(2) "01"
  [4]=>
  string(2) "02"
  [5]=>
  string(2) "03"
  [6]=>
  string(2) "04"
  [7]=>
  string(2) "05"
}
Community
  • 1
  • 1
alex
  • 479,566
  • 201
  • 878
  • 984
12

Using the new datetime component (PHP >= 5.3.0) you can use a combination of DateTime, DateInterval and DatePeriod to get an iterator over all weeks in the given timespan.

$p = new DatePeriod(
    new DateTime('2011-12-01'), 
    new DateInterval('P1W'), 
    new DateTime('2012-02-01')
);
foreach ($p as $w) {
    var_dump($w->format('W'));
}

/*
string(2) "48"
string(2) "49"
string(2) "50"
string(2) "51"
string(2) "52"
string(2) "01"
string(2) "02"
string(2) "03"
string(2) "04"
*/
Stefan Gehrig
  • 82,642
  • 24
  • 155
  • 189
0

use a combo of date( 'W' ) and strtotime( '+1 week', $time ) in a loop

Galen
  • 29,976
  • 9
  • 71
  • 89