我需要计算两个或更多个日期范围(开始和结束日期)中唯一天的数量。当日期开始重叠时出现问题(请参见下面的示例)。
总天数:23天
唯一天总数: 20天
要处理的数据很多,日期可能跨很长一段时间,因此我需要一种有效而快速的方法来进行计算。该项目在Laravel 5中构建。
谢谢
答案 0 :(得分:0)
请注意,第一个示例是6天的差异,而不是7天。
代码
<?php
$dateRanges =
[
[
'start' => "2019-06-01",
'end' => "2019-06-07",
],
[
'start' => "2019-06-05",
'end' => "2019-06-10",
],
[
'start' => "2019-06-20",
'end' => "2019-06-30",
]
];
$uniqueDayDiffCount = 0;
foreach($dateRanges as $dateRange) {
$start = new DateTime($dateRange['start']);
$end = new DateTime($dateRange['end']);
$first = $start;
/**
* Check if a new $start date overlaps
* with the prvious end date ($last) and if so
* take for calcualtion as start
* date ($first) the previous
* end date ($last)
*/
if (isset($last) && $last > $start) {
$first = $last;
}
$last = $end;
echo "\n<br>Start: " . $start->format("Y-m-d");
echo "\n<br>End: " . $end->format("Y-m-d");
echo "\n<br>Calc for Start: " . $first->format("Y-m-d");
echo "\n<br>Calc for End: " . $last->format("Y-m-d");
$diff = $last->diff($first)->format("%a");
$uniqueDayDiffCount += $diff;
echo "\n<br>Diff: $diff\n<br>DayCount: $uniqueDayDiffCount";
echo "\n<br>---------------------\n<br>";
}
echo "\n<br>Total DayCount: $uniqueDayDiffCount";
结果
Start: 2019-06-01
End: 2019-06-07
Calc for Start: 2019-06-01
Calc for End: 2019-06-07
Diff: 6
DayCount: 6
---------------------
Start: 2019-06-05
End: 2019-06-10
Calc for Start: 2019-06-07
Calc for End: 2019-06-10
Diff: 3
DayCount: 9
---------------------
Start: 2019-06-20
End: 2019-06-30
Calc for Start: 2019-06-20
Calc for End: 2019-06-30
Diff: 10
DayCount: 19
---------------------
Total DayCount: 19
答案 1 :(得分:0)
使用Carbon,您可以为每个范围添加“开始”和“结束”之间的所有日期,并针对每个插入内容,检查当前日期是否不在数组中。
您最终将获得所有唯一日期的数组,并且可以count
。