How to list all months between two dates
function getMonthsInRange($startDate, $endDate)
{
$months = array();
while (strtotime($startDate) <= strtotime($endDate)) {
$months[] = array(
'year' => date('Y', strtotime($startDate)),
'month' => date('m', strtotime($startDate)),
);
// Set date to 1 so that new month is returned as the month changes.
$startDate = date('01 M Y', strtotime($startDate . '+ 1 month'));
}
return $months;
}
This was my solution since DateTime is not available in my server environment.
$a = "2007-01-01";
$b = "2008-02-15";
$i = date("Ym", strtotime($a));
while($i <= date("Ym", strtotime($b))){
echo $i."\n";
if(substr($i, 4, 2) == "12")
$i = (date("Y", strtotime($i."01")) + 1)."01";
else
$i++;
}
Try it out: http://3v4l.org/BZOmb
You must make a difference between two months of the same year and two months of different years.
$year_min = substr($row['contractStart'], 0, 4);
$year_max = substr($row['contractEnd'], 0, 4);
$month_min = substr($row['contractStart'], 5, 2);
$month_min = substr($row['contractEnd'], 5, 2);
$period = array();
try {
if ($year_min > $year_max)
throw new Exception();
else if ($year_min == $year_max)
if ($month_min > $month_max)
throw new Exception();
for ($month = $month_min; $month <= $month_max; $month++) {
$period[] = $month . '-' . $year;
}
else {
for ($month = $month_min; $month <= 12; $month++) {
$period[] = $month . '-' . $year_min;
}
for ($year = $year_min + 1; $year < $year_max; $year++) {
for ($month = $month_min; $month <= $month_max; $month++) {
$period[] = $month . '-' . $year;
}
}
for ($month = 1; $month <= $month_max; $month++) {
$period[] = $month . '-' . $year_max;
}
}
implode("<br />\r\n", $period);
}
catch (Exception $e) {
echo 'Start date occurs after end date.'
}
That's for the hard way. Now there is a quick and easy way that is already given as an answer which I recommend you to choose.
PHP 5.3
$start = new DateTime('2010-12-02');
$start->modify('first day of this month');
$end = new DateTime('2012-05-06');
$end->modify('first day of next month');
$interval = DateInterval::createFromDateString('1 month');
$period = new DatePeriod($start, $interval, $end);
foreach ($period as $dt) {
echo $dt->format("Y-m") . "<br>\n";
}
See it in action
PHP 5.4 or newer
$start = (new DateTime('2010-12-02'))->modify('first day of this month');
$end = (new DateTime('2012-05-06'))->modify('first day of next month');
$interval = DateInterval::createFromDateString('1 month');
$period = new DatePeriod($start, $interval, $end);
foreach ($period as $dt) {
echo $dt->format("Y-m") . "<br>\n";
}
The part where we modify the start and end dates to the first of the month is important. If we didn't, and the current day higher then the last day in February (i.e. 28 in non-leap years, 29 in leap years) this would skip February.