-
眼眸繁星
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";}PHP 5.4或更高版本$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";}我们将开始日期和结束日期修改为每月第一天的部分很重要。如果我们不这样做,则当前日期要比2月的最后一天高(例如,非-年为28,leap年为29),则跳过2月。
-
慕斯709654
您必须在同一年的两个月与不同年份的两个月之间有所不同。$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.'}那是艰难的方式。现在,已经有一种快速简便的方法作为答案,我建议您选择该方法。
-
慕容3067478
function getMonthsInRange($startDate, $endDate) {$months = array();while (strtotime($startDate) <= strtotime($endDate)) { $months[] = array('year' => date('Y', strtotime($startDate)), 'month' => date('m', strtotime($startDate)), ); $startDate = date('d M Y', strtotime($startDate. '+ 1 month'));}return $months;}