我想找到两个DatePeriods给出的重叠分钟数。
例如,
(为了演示,格式为'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分钟重叠的结果。怎么能实现这一目标?
这个问题被标记为重复,但它们不一样。我在两个 DatePeriods 中寻找重叠时间的数量,而不是两个日期之间的差异。 “DatePeriod”由两个日期组成,我正在寻找两个DatePeriod之间重叠(不是差异)的数量。
答案 0 :(得分:0)
这是类 DatePeriodsOverlap ,它表示两个句点的重叠。 如果没有交集,则结果是重叠 DatePeriod 或例外。
注意:DatePeriod是可遍历的对象,PT1M是迭代步骤的持续时间。 PT1M 表示一分钟的间隔。详细信息about DateInterval对象。
使用示例和问题答案,如何在几分钟内重叠:
<?php
$d1 = new DatePeriod(
new DateTime('2015-09-11 09:15:00'),
new DateInterval('PT1M'),
new DateTime('2015-09-13 11:30:00')
);
$d2 = new DatePeriod(
new DateTime('2015-09-13 10:45:00'),
new DateInterval('PT1M'),
new DateTime('2015-09-14 12:00:00')
);
$overlapPeriod = (new DatePeriodsOverlap(
$d1,
$d2,
new DateInterval('PT1M')) // PT1M - 1 minute interval,
// P1D - 1 day interval
)->overlap();
$minutes = iterator_count($overlapPeriod); // 45 minutes
// interval in minutes without iterating
$overlapPeriod->getEndDate()
->diff($overlapPeriod->getStartDate())
->i; // is interval in minutes (H:i:s)
/**
* Overlap of two periods
*/
class DatePeriodsOverlap {
private $d1;
private $d2;
private $di; // DateInterval, default is 1 day
/**
* @param DatePeriod $d1 first period
* @param DatePeriod $d2 second period
* @param DateInterval $di interval measurement
*/
public function __construct(
DatePeriod $d1,
DatePeriod $d2,
DateInterval $di = null)
{
$this->d1 = $d1;
$this->d2 = $d2;
$this->di = $di ?? new DateInterval('P1D');
}
/**
* Returns new overlapping period
*
* @throws Exception if not overlapped
* @return DatePeriod
*/
public function overlap() : DatePeriod
{
$startOne = $this->d1->getStartDate();
$endOne = $this->d1->getEndDate();
$startTwo = $this->d2->getStartDate();
$endTwo = $this->d2->getEndDate();
//If the dates overlap
if ($startOne < $endTwo && $endOne > $startTwo)
{
return new DatePeriod(
max($startTwo,$startOne),
$this->di,
min($endOne,$endTwo)
);
}
throw new Exception(
"No overlap " .
"[{$this->d1->getStartDate()->format('Y-m-d H:i:s')}-{$this->d1->getEndDate()->format('Y-m-d H:i:s')}] and " .
"[{$this->d2->getStartDate()->format('Y-m-d H:i:s')}-{$this->d2->getEndDate()->format('Y-m-d H:i:s')}]"
);
}
}