<?php
/**
* 获取指定月份段内每一个月份
* @param Date $startmonth 开始日期
* @param Date $endmonth 结束日期
* @return Array
*/
function getMonthFromRange($startmonth, $endmonth) {
$stimestamp = strtotime($startmonth);
$etimestamp = strtotime($endmonth);
// 计算日期段内有多少天
// $days = ($etimestamp-$stimestamp)/86400+1;
$y = date('Y', $stimestamp);
$ys = date('Y', $etimestamp);
$m = (int)date('m', $stimestamp);
$ms = (int)date('m', $etimestamp);
$chaY = $ys-$y;
//月份相差多少
$chaM = 12-$m + $ms;
//相差一年就加12
$yearmeth = $chaM + (($chaY-1) *12);
//echo $yearmeth;
// 保存每天日期
$month = array();
for ($i = 0; $i <= $yearmeth; $i++) {
$month[] = date('Y-m', strtotime("+{$i}month",$stimestamp));
}
return $month;
}
$startdate = '2021-08';
$enddate = '2022-09';
// demo
$date = getMonthFromRange($startdate, $enddate);
print_r($date);
网友回复