Display all the week numbers between two dates in PHP [duplicate]
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.
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"
}
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"
*/
use a combo of date( 'W' )
and strtotime( '+1 week', $time )
in a loop
精彩评论