I have two dates - a start date and an end date. I need to return an array of months ('Y-m' format) which includes every month between start and end date, as well as the months that those dates are in. I've tried:
$start = strtotime('2010-08-20');
$end = strtotime('2010-09-15');
$month = $start;
while($month <= $end) {
$months[] = date('Y-m', $month);
$month = strtotime("+1 month", $month);
}
The problem is that, in the above example, it only adds '2010-08' to the array, and not '2010-09'. I feel like the solution should be obvious, but I just can't see it.
Note that this should take into account situations like:
$start = strtotime('2010-08-20');
$end = strtotime('2010-08-21');
// should return '2010-08'
$start = strtotime('2010-08-20');
$end = strtotime('2010-09-01');
// should return '2010-08,2010-09'
$start = strtotime('2010-08-20');
$end = strtotime('2010-10-21');
// should return '2010-08,2010-09,2010-10'
Also, the version of PHP on my host is 5.2.6 so it has to work within those confines.
The solution I used was based on the answer below re. setting $start
to the first day of the month. However I couldn't get it working with just the strtotime()
and instead had to use another function I found on the web.
function firstDayOfMonth($uts=null)
{
$today = is_null($uts) ? getDate() : getDate($uts);
$first_day = getdate(mktime(0,0,0,$today['mon'],1,$today['year']));
return $first_day[0];
}
$start = strtotime('2010-08-20');
$end = strtotime('2010-09-15');
$month = firstDayOfMonth($start);
while($month <= $end) {
$months[] = date('Y-m', $month);
$month = strtotime("+1 month", $month);
}