本文实例讲述了yii 框架实现按天,月,年,自定义时间段统计数据的方法。分享给大家供大家参考,具体如下:
天(day): 格式Y-m-d
月(month):格式Y-m
年(year):格式Y
时间段(range): 格式Y-m-d
首先计算时间
天0-23小时
$rangeTime = range(0, 23);
月:1-月底
// $days = cal_days_in_month(CAL_GREGORIAN, $month, $year); $days = date("t",strtotime($year . '-' . $month)); // 生成1-days的天 $rangeTime = range(1, $days);
年:1-12月
$rangeTime = range(1, 12);
时间段;开始时间-结束时间
$stimestamp = strtotime($time); $etimestamp = strtotime($time2); // 计算日期段内有多少天 $days = ($etimestamp - $stimestamp) / 86400 + 1; // 保存每天日期 for($i = 0; $i < $days; $i++){ $newTimeStamp = $stimestamp + (86400 * $i); $rangeTime[] = date('Y-m-d', $newTimeStamp); $labels[] = date('d', $newTimeStamp) . Yii::t('backend', 'day'); }
封装一下
/** * 获取label和时间段 * type: day, month, year, range * time: 日期; day为具体的天y-m-d, month为具体的月y-m, year为具体的年y * time2 日期, 时间段的第二个时间 */ public function getLabelAndRangeTime($type, $time, $time2) { if(empty($time)) { $time = date('Y-m-d', time()); } $labels = []; $rangeTime = []; if($type == 'day') { // 生成1-24小时 $rangeTime = range(0, 23); foreach ($rangeTime as $key => $val) { $label = $val . Yii::t('backend', 'hour'); $labels[] = $label; } } else if($type == 'month') { $dateArr = explode('-', $time); if(count($dateArr > 1)) { $year = $dateArr[0]; $month = $dateArr[1]; $time = $year; $time2 = $month; // 获取当前年月的天数 // $days = cal_days_in_month(CAL_GREGORIAN, $month, $year); $days = date("t",strtotime($year . '-' . $month)); // 生成1-days的天 $rangeTime = range(1, $days); foreach ($rangeTime as $key => $val) { $label = $val . Yii::t('backend', 'day'); $labels[] = $label; } } } else if($type == 'year') { // 生成1-12月 $rangeTime = range(1, 12); foreach ($rangeTime as $key => $val) { $label = $val . Yii::t('backend', 'month'); $labels[] = $label; } } else if($type == 'range') { $stimestamp = strtotime($time); $etimestamp = strtotime($time2); // 计算日期段内有多少天 $days = ($etimestamp - $stimestamp) / 86400 + 1; // 保存每天日期 for($i = 0; $i < $days; $i++){ $newTimeStamp = $stimestamp + (86400 * $i); $rangeTime[] = date('Y-m-d', $newTimeStamp); $labels[] = date('d', $newTimeStamp) . Yii::t('backend', 'day'); } } return [ 'type' => $type, 'time' => $time, 'time2' => $time2, 'rangeTime' => $rangeTime, 'labels' => $labels ]; }
内容版权声明:除非注明,否则皆为本站原创文章。