<?php
public function divideTimeRangeByIntervalWithExclusion($startDate, $endDate, $startTimeRange, $endTimeRange, $interval, $excludeStartTime = null, $excludeEndTime = null) {
$startDateTimeStamp = strtotime($startDate);
$endDateTimeStamp = strtotime($endDate);
if ($startDateTimeStamp === false || $endDateTimeStamp === false) {
return false; // 处理无效的日期格式
}
$segments = [];
$currentDate = $startDateTimeStamp;
while ($currentDate <= $endDateTimeStamp) {
$startTimeStamp = strtotime(date('Y-m-d', $currentDate) . ' ' . $startTimeRange);
$endTimeStamp = strtotime(date('Y-m-d', $currentDate) . ' ' . $endTimeRange);
$excludeStartTimeStamp = $excludeStartTime ? strtotime(date('Y-m-d', $currentDate) . ' ' . $excludeStartTime) : null;
$excludeEndTimeStamp = $excludeEndTime ? strtotime(date('Y-m-d', $currentDate) . ' ' . $excludeEndTime) : null;
$currentSegmentStart = $startTimeStamp;
while ($currentSegmentStart < $endTimeStamp) {
$currentSegmentEnd = $currentSegmentStart + $interval;
if ($currentSegmentEnd > $endTimeStamp) {
$currentSegmentEnd = $endTimeStamp;
}
// 检查是否在排除时间段内,如果是,则跳过这个段
if (
($excludeStartTimeStamp !== null && $excludeEndTimeStamp !== null) &&
($currentSegmentStart >= $excludeStartTimeStamp && $currentSegmentStart < $excludeEndTimeStamp)
) {
$currentSegmentStart = $excludeEndTimeStamp;
continue;
}
$segments[] = [
'start' => date('H:i', $currentSegmentStart),
'end' => date('H:i', $currentSegmentEnd)
];
$currentSegmentStart = $currentSegmentEnd;
}
$currentDate = strtotime('+1 day', $currentDate);
}
return $segments;
}
$startDate = '2023-08-01';
$endDate = '2023-08-02';
$startTimeRange = '01:00:00';
$endTimeRange = '18:00:00';
$interval = 3600; // 10分钟,以秒为单位
$excludeStartTime = '';//'10:00:00';
$excludeEndTime = '';//'11:00:00';
$segments = divideTimeRangeByIntervalWithExclusion($startDate, $endDate, $startTimeRange, $endTimeRange, $interval, $excludeStartTime, $excludeEndTime);
if ($segments !== false) {
foreach ($segments as $segment) {
echo "Start: {$segment['start']}, End: {$segment['end']}\n";
}
} else {
echo "Invalid input or calculation error.";
}
将一个时间范围分割成多个时间段,每个时间段的长度由给定的时间间隔 ($interval) 决定,并且可以排除指定的时间段。
最新推荐文章于 2024-01-17 10:17:22 发布