获取两个日期之间的月份
$s = '2019-02-05';
$e = '2019-07-20';
$start = new \DateTime($s);
$end = new \DateTime($e);
// 时间间距 这里设置的是一个月
$interval = \DateInterval::createFromDateString('1 month');
$period = new \DatePeriod($start, $interval, $end);
foreach ($period as $dt) {
echo $dt->format("Y-m") . "
\n";
}
输出结果:2019-03
2019-04
2019-05
2019-06
扩展知识
$s = '2019-02-05';
$e = '2019-07-20';
// 获取首月的月初和月末日期
if (date('j', strtotime($s)) > 1) {
$start_day_head = date('Y-m-01', strtotime($s));
$end_day_head = date('Y-m-t', strtotime($s));
$s = date('Y-m-01', strtotime("+1 months", strtotime($s)));
}
// 获取末月的月初和月末日期
if (date('j', strtotime($e)) > 1) {
$start_day_tail = date('Y-m-01', strtotime($e));
$end_day_tail = date('Y-m-t', strtotime($e));
$e = date('Y-m-t', strtotime("-1 months", strtotime($e)));
}
输出:2019-02-01
2019-02-28
2019-03-01
2019-07-01
2019-07-31
2019-06-30