获取连续日期区间
/**
* 获取连续日期区间
* @param $dateArr
* @return array
*/
function getDateInterval($dateArr): array
{
$dateArr = array_unique($dateArr);
sort($dateArr);
$result = [];
$interval = [];
$cnt = count($dateArr);
foreach ($dateArr as $key => $date) {
if ($key == 0) {
$interval['start'] = $date;
}
if ($key < ($cnt - 1) && strtotime($date) + 86400 == strtotime($dateArr[$key + 1])) {
continue;
} else {
$interval['end'] = $date;
$result[] = $interval;
if ($key < ($cnt - 1)) {
$interval['start'] = $dateArr[$key + 1];
}
}
}
return $result;
}
使用
getDateInterval(['2021-01-01', '2021-01-02', '2021-01-04', '2021-01-06', '2021-01-07'])
返回
array(3) {
[0]=>
array(2) {
["start"]=>
string(10) "2021-01-01"
["end"]=>
string(10) "2021-01-02"
}
[1]=>
array(2) {
["start"]=>
string(10) "2021-01-04"
["end"]=>
string(10) "2021-01-04"
}
[2]=>
array(2) {
["start"]=>
string(10) "2021-01-06"
["end"]=>
string(10) "2021-01-07"
}
}
切割时间段
function splitDateRange($startDate, $endDate, int $step = 7): array
{
$result = [];
$step = $step < 1 ? 1 : $step - 1;
$startDate = date("Y-m-d", strtotime($startDate));
$endDate = date("Y-m-d", strtotime($endDate));
do {
$tmpEndDate = date('Y-m-d', strtotime($startDate. " +{$step} day"));
if (strtotime($tmpEndDate) >= strtotime($endDate)) {
$tmpEndDate = $endDate;
$result[] = [$startDate . " 00:00:00", $tmpEndDate . " 23:59:59"];
break;
} else {
$result[] = [$startDate . " 00:00:00", $tmpEndDate . " 23:59:59"];
$startDate = date('Y-m-d', strtotime($tmpEndDate. " +1 day"));
}
} while (true);
return $result;
}
使用
splitDateRange('2021-01-01', '2021-01-31')
返回
array(5) {
[0]=>
array(2) {
[0]=>
string(19) "2021-01-01 00:00:00"
[1]=>
string(19) "2021-01-07 23:59:59"
}
[1]=>
array(2) {
[0]=>
string(19) "2021-01-08 00:00:00"
[1]=>
string(19) "2021-01-14 23:59:59"
}
[2]=>
array(2) {
[0]=>
string(19) "2021-01-15 00:00:00"
[1]=>
string(19) "2021-01-21 23:59:59"
}
[3]=>
array(2) {
[0]=>
string(19) "2021-01-22 00:00:00"
[1]=>
string(19) "2021-01-28 23:59:59"
}
[4]=>
array(2) {
[0]=>
string(19) "2021-01-29 00:00:00"
[1]=>
string(19) "2021-01-31 23:59:59"
}
}