我刚刚问过这个问题并且它已被标记为已经回答,但无论是谁做了这个问题显然都不明白这个问题.
这篇文章被标记为重复的问题,
但它们甚至不是一样的.
我正在寻找两个DatePeriods中的重叠时间量,而不是两个日期之间的差异.
"DatePeriod"由两个日期组成,我正在寻找两个DatePeriod之间的重叠量.
还有另一篇文章,我发现这里回答了我的一半问题,
并且它工作得很好,但它没有给我两个日期范围之间重叠的时间量.它只确定它们是否重叠.我需要知道它们重叠的分钟数.所以这是我原来的问题......
我假设有一个非常简单的方法可以做到这一点,但我已经看了一遍,找不到解决方案.逻辑很简单:找到给定两个DatePeriods的重叠分钟数.
例如,
- 我有$startDate1和$endDate1作为第一个日期范围.
- 我有$startDate2和$endDate2作为第二个日期范围.
(为了演示,格式是'Y-m-d H:i'.)
假设$startDate1 = '2015-09-11 09:15'和$endDate1 = '2015-09-13 11:30'.
假设$startDate2 = '2015-09-13 10:45'和$endDate2 = '2015-09-14 12:00'.
我希望45分钟重叠的结果.怎么能实现这一目标?
我已经看到这使用两个DateTimes完成,但这不是我正在寻找的.
datePeriod由两个DateTime组成,我正在寻找两个DatePeriod之间的差异.
正如我在评论中所解释的那样,有四个步骤.
这是一个做你想做的事情的功能:
/**
* What is the overlap, in minutes, of two time periods?
*
* @param $startDate1 string
* @param $endDate1 string
* @param $startDate2 string
* @param $endDate2 string
* @returns int Overlap in minutes
*/
function overlapInMinutes($startDate1, $endDate1, $startDate2, $endDate2)
{
// Figure out which is the later start time
$lastStart = $startDate1 >= $startDate2 ? $startDate1 : $startDate2;
// Convert that to an integer
$lastStart = strtotime($lastStart);
// Figure out which is the earlier end time
$firstEnd = $endDate1 <= $endDate2 ? $endDate1 : $endDate2;
// Convert that to an integer
$firstEnd = strtotime($firstEnd);
// Subtract the two, divide by 60 to convert seconds to minutes, and round down
$overlap = floor( ($firstEnd - $lastStart) / 60 );
// If the answer is greater than 0 use it.
// If not, there is no overlap.
return $overlap > 0 ? $overlap : 0;
}
Run Code Online (Sandbox Code Playgroud)
样品用途:
$startDate1 = '2015-09-11 09:15';
$endDate1 = '2015-09-13 11:30';
$startDate2 = '2015-09-13 10:45';
$endDate2 = '2015-09-14 12:00';
echo overlapInMinutes($startDate1, $endDate1, $startDate2, $endDate2) . "\n";
// echoes 45
$startDate1 = '2015-09-11 09:15';
$endDate1 = '2015-09-13 11:30';
$startDate2 = '2015-09-13 12:45';
$endDate2 = '2015-09-14 12:00';
echo overlapInMinutes($startDate1, $endDate1, $startDate2, $endDate2) . "\n";
// echoes 0
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1140 次 |
| 最近记录: |