Given a start and end date, I need to generate an array with year and week values. For example:
Start Date: 2013-01-01
End Date: 2013-02-23
Generated Array:
Array ( [0] => Array ( [week] => 01 [year] => 2013 ) [1] => Array ( [week] => 02 [year] => 2013 ) [2] => Array ( [week] => 03 [year] => 2013 ) [3] => Array ( [week] => 04 [year] => 2013 ) [4] => Array ( [week] => 05 [year] => 2013 ) [5] => Array ( [week] => 06 [year] => 2013 ) [6] => Array ( [week] => 07 [year] => 2013 ) [7] => Array ( [week] => 08 [year] => 2013 ) )
Here is the code I'm using to generate this:
public static function getYearWeekRange($startdate, $enddate) {
$array = array();
$starttime = strtotime($startdate);
$endtime = strtotime($enddate);
while ($starttime <= $endtime) {
$year = date('Y', $starttime);
$week = date('W', $starttime);
$array[] = array('week' => $week, 'year' => $year);
$starttime = strtotime('+1 week', $starttime);
}
return $array;
}
My problem is that when I generate certain date ranges, I don't get the correct year value at the start of the 2013 year. For example:
Start Date: 2012-01-01
End Date: 2013-02-23
In this case, where it should have an subarray with year = 2013 and week = 01, it actually has it's year value equal to 2012.
If I were to switch the start date to 2013-01-05 for example, then there is no problem.
Can anyone offer a solution that would guarantee that my year and week values are always correct?