将一个时间范围分割成多个时间段,每个时间段的长度由给定的时间间隔 ($interval) 决定,并且可以排除指定的时间段。

<?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.";
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值