最近要做日/周/月/季的后台数据图表,把探索出的关于自然周的方法记录在这里
- 按自然周切割时间:
说明:第一周起始时间为参数beginDateStr
所在周,最后一周起始时间为距离参数endDateStr
最近的那周。(若endDateStr
为星期二,则最后一周是[上周一,上周日];若endDateStr
为星期日,则最后一周是[本周一,本周日])
/**
* 根据时间段,获取其间各自然周时间戳
* @param string $beginDateStr
* @param string $endDateStr
*/
public static function getSchemeDateWeekly($beginDateStr = '', $endDateStr = '')
{
$beginTimestamp = strtotime(date($beginDateStr));
$beginWeekRange = self::actionWeek($beginDateStr);
$endWeekRange = self::actionWeek($endDateStr);
if ($beginWeekRange['end'] < $beginTimestamp) {
$beginDateStr = date('Y-m-d', $beginWeekRange['end'] + (7 * 24 * 60 * 60));
$beginWeekRange = self::actionWeek($beginDateStr);
}
$begin_date = date('Y-m-d', $beginWeekRange['start']);
$end_date = date('Y-m-d', $endWeekRange['end']);
$weekList = (new DateTimeUtils)->getSchemeDate7days($begin_date, $end_date);
return $weekList;
}
// 根据时间段按7天来分割时间
function getSchemeDate7days($begin_date = '', $end_date = '')
{
if (!$begin_date || !$end_date) return false;
$diff_time = strtotime($end_date) + 24 * 60 * 60 - strtotime($begin_date);
$diff_week = round($diff_time / (7 * 24 * 60 * 60));
$times_arr = [];
foreach (range(0, $diff_week - 1) as $item) {
$times_arr[$item]['begin_date'] = date('Y-m-d', strtotime($begin_date) + (7 * 24 * 60 * 60) * $item);
$times_arr[$item]['end_date'] = date('Y-m-d', strtotime($times_arr[$item]['begin_date']) + (6 * 24 * 60 * 60));
if (strtotime($times_arr[$item]['end_date']) > strtotime($end_date)) {
unset($times_arr[$item]);
}
}
return $times_arr;
}
// 根据时间获取最近的自然周起止时间的时间戳
static function actionWeek($timeStr = '')
{
$time = strtotime(date($timeStr));
$startTimestamp = strtotime(date(
"Y-m-d H:i:s",
mktime(0, 0, 0, date("m", $time),
date("d", $time) - date("w", $time) + 1 - 7,
date("Y", $time)
)
));
$endTimestamp = strtotime(date(
"Y-m-d H:i:s",
mktime(23, 59, 59,
date("m", $time),
date("d", $time) - date("w", $time) + 7 - 7,
date("Y", $time)
)
));
return ['start' => $startTimestamp, 'end' => $endTimestamp];
}
测试用例:
var_dump(getSchemeDateWeekly("2021-03-07", "2021-07-09"))
输出如下: