v-matsuk/time-overlap-calculator

时间重叠计算器

1.0.0 2017-07-11 22:15 UTC

This package is not auto-updated.

Last update: 2024-09-28 20:09:04 UTC


README

=========================

Build Status codecov

这是一个轻量级的库,帮助处理日期/时间重叠。

安装

$ composer require v-matsuk/time-overlap-calculator

使用方法

<?php

use VM\TimeOverlapCalculator\TimeOverlapCalculator;
use VM\TimeOverlapCalculator\Entity\TimeSlot;
use VM\TimeOverlapCalculator\Generator\TimeSlotGenerator;

$calculator = new TimeOverlapCalculator();

$baseTimeSlot = new TimeSlot(
    new \DateTime('2016-01-01 08:00'),
    new \DateTime('2016-01-01 20:00')
);
$overlappingTimeSlot = new TimeSlot(
   new \DateTime('2016-01-01 13:00'),
   new \DateTime('2016-01-01 17:00')
);

检查两个时间段是否有重叠

$isOverlap = $calculator->isOverlap($baseTimeSlot, $overlappingTimeSlot); //will return true

计算重叠部分的大小,并将结果转换为指定的单位(默认为秒)

$resultInSeconds = $calculator->calculateOverlap($baseTimeSlot, $overlappingTimeSlot); //14400
$resultInMinutes = $calculator->calculateOverlap($baseTimeSlot, $overlappingTimeSlot, TimeOverlapCalculator::TIME_UNIT_MINUTE); //240
$resultInHours = $calculator->calculateOverlap($baseTimeSlot, $overlappingTimeSlot, TimeOverlapCalculator::TIME_UNIT_HOUR); //4

生成一个非重叠时间段数组

//will return array that contains two time slots:
//from 2016-01-01 08:00 till 2016-01-01 13:00 and from 2016-01-01 17:00 till 2016-01-01 20:00
$timeSlotGenerator = new TimeSlotGenerator();
$freeTimeSlots = $calculator->getNonOverlappedTimeSlots(
    $baseTimeSlot,
    [$overlappingTimeSlot],
    $timeSlotGenerator
);

TimeSlotGenerator用于生成在从基本时间段排除所有重叠时间段后出现的新时间段。

将重叠时间段合并为单个时间段

//will return array that contains two time slots:
//from 2016-01-01 10:00 till 2016-01-01 16:00 and from 2016-01-01 19:00 till 2016-01-01 22:00
$timeSlotGenerator = new TimeSlotGenerator();
$freeTimeSlots = $calculator->mergeOverlappedTimeSlots(
    $timeSlotGenerator,
    [
        new TimeSlot(new \DateTime('2016-01-01 13:00'), new \DateTime('2016-01-01 16:00')),
        new TimeSlot(new \DateTime('2016-01-01 11:00'), new \DateTime('2016-01-01 14:00')),
        new TimeSlot(new \DateTime('2016-01-01 19:00'), new \DateTime('2016-01-01 22:00')),
        new TimeSlot(new \DateTime('2016-01-01 10:00'), new \DateTime('2016-01-01 13:00')),
    ]
);

TimeSlotGenerator用于生成在所有重叠时间段合并后出现的新时间段。

您可以使用自己的TimeSlot实现。您的类应实现TimeSlotInterface。您还可以使用自定义的TimeSlotGenerator。您的类应实现TimeSlotGeneratorInterface。