php获取指定时间范围内所有的月开始到结束
示例:
$time_slot = '2019-11-15,2020-01-25'
返回结果:
[ "2019-11-15,2019-11-30", "2019-12-01,2019-12-31","2020-01-01,2020-01-25" ]
代码如下:
public function time_slot_list($time_slot){
//获取时间范围始末
$time_slot_start = explode(',',$time_slot)[0];
$time_slot_end = explode(',',$time_slot)[1];
// 获取始末年份
$start_year_ident = explode('-',$time_slot_start)[0];
$end_year_ident = explode('-',$time_slot_end)[0];
// 获取始末月份
$start_ident = explode('-',$time_slot_start)[1];
$end_ident = explode('-',$time_slot_end)[1];
if ($start_year_ident == $end_year_ident){
//如果为同月,相当于全部统计
if ($start_ident == $end_ident){
$time_slot_list[] = $time_slot;
}else{
//判断月份间隔
$num = (int)$end_ident - (int)$start_ident;
$i=0;
//生成逐月数据
while ($i<=$num){
if ($i==0){
$firstday = date('Y-m-01', strtotime($time_slot_start));
$lastday = date('Y-m-d', strtotime("$firstday +1 month -1 day"));
$time_slot_list[] = $time_slot_start.",".$lastday;
}elseif ($i==$num){
$firstday = date('Y-m-01', strtotime($time_slot_end));
$time_slot_list[] = $firstday.",".$time_slot_end;
}else{
$firstday = date('Y-m-01', strtotime("$time_slot_start +$i month"));
$lastday = date('Y-m-d', strtotime("$firstday +1 month -1 day"));
$time_slot_list[] = $firstday.",".$lastday;
}
$i++;
}
}
}else{
//如果为同月,相当于统计几年的每个月
if ($start_ident == $end_ident){
//判断月份间隔
$num = ((int)$end_year_ident - (int)$start_year_ident)*12;
$i=0;
//生成逐月数据
while ($i<=$num){
if ($i==0){
$firstday = date('Y-m-01', strtotime($time_slot_start));
$lastday = date('Y-m-d', strtotime("$firstday +1 month -1 day"));
$time_slot_list[] = $time_slot_start.",".$lastday;
}elseif ($i==$num){
$firstday = date('Y-m-01', strtotime($time_slot_end));
$time_slot_list[] = $firstday.",".$time_slot_end;
}else{
$firstday = date('Y-m-01', strtotime("$time_slot_start +$i month"));
$lastday = date('Y-m-d', strtotime("$firstday +1 month -1 day"));
$time_slot_list[] = $firstday.",".$lastday;
}
$i++;
}
}else{
//判断月份间隔
$num = ((int)$end_year_ident - (int)$start_year_ident)*12 - (int)$start_ident + (int)$end_ident;
$i=0;
//生成逐月数据
while ($i<=$num){
if ($i==0){
$firstday = date('Y-m-01', strtotime($time_slot_start));
$lastday = date('Y-m-d', strtotime("$firstday +1 month -1 day"));
$time_slot_list[] = $time_slot_start.",".$lastday;
}elseif ($i==$num){
$firstday = date('Y-m-01', strtotime($time_slot_end));
$time_slot_list[] = $firstday.",".$time_slot_end;
}else{
$firstday = date('Y-m-01', strtotime("$time_slot_start +$i month"));
$lastday = date('Y-m-d', strtotime("$firstday +1 month -1 day"));
$time_slot_list[] = $firstday.",".$lastday;
}
$i++;
}
}
}
return $time_slot_list;
}