在做数据统计图表时,需要计算一个时间段内的周数量,每周的开始时间和结束时间;
下面是php的实现方法:
/**
* 获取指定时间段内有几周,每周的开始日期和结束日期
* @return [] [[s:开始日期,e:结束日期],[s:开始日期,e:结束日期]]
*/
function count_weeks($start_string, $end_string = '')
{
$startDate = date('Y-m-d', strtotime($start_string) );
if(empty($end_string)) {
$endDate = date('Y-m-d');
}else{
$endDate = date('Y-m-d', strtotime($end_string));
}
$sw = date("Ymw",strtotime($startDate));
$ew = date("Ymw",strtotime($endDate));
if($sw == $ew){
$weekList[] =array('s'=> date("Y-m-d",strtotime("this week 00:00:00", strtotime($startDate))), 'e'=> date("Y-m-d",strtotime("next week 00:00:00 -1second", strtotime($endDate))));
}else{
$week_end = date("Y-m-d",strtotime("next week 00:00:00 -1second", strtotime($startDate)));
$weekList[] = array('s'=>date("Y-m-d", strtotime("this week 00:00:00", strtotime($startDate))),
'e'=> date("Y-m-d",strtotime("next week 00:00:00 -1second", strtotime($startDate))) );
if($week_end >= $endDate){
$weekList[] = array('s'=> strtotime("this week 23:59:59", strtotime($startDate)),
'e'=> strtotime("next week 00:00:00", strtotime($endDate)));
}else{
while($week_end <= $endDate){
$start = date("Y-m-d",strtotime(" +1 day", strtotime($week_end)));
$week_end = date("Y-m-d",strtotime("next week 00:00:00 -1second", strtotime($start)));
if($week_end <= $endDate){
$weekList[] = array('s'=>$start, 'e'=>date("Y-m-d",strtotime("$week_end")));
}else{
$weekList[] = array('s'=>$start, 'e'=>date("Y-m-d",strtotime("next week 00:00:00 -1second",strtotime("$endDate") )));
}
}
}
}
return $weekList;
}
好了,本文内容全部结束,感谢您的阅读,希望能帮助到你。