PHP Period Date: Compare and calculate dates between time periods

Recommend this page to a friend!
  Info   View files Documentation   View files View files (25)   DownloadInstall with Composer Download .zip   Reputation   Support forum   Blog    
Last Updated Ratings Unique User Downloads Download Rankings
2020-07-22 (Yesterday) RSS 2.0 feedNot yet rated by the usersTotal: Not yet counted Not yet ranked
Version License PHP version Categories
period 1.0Custom (specified...5PHP 5, Time and Date
Description Author

This package can compare and calculate dates between time periods.

It can take the date and time of two moments and perform operations concerning the time interval between those moments. Currently it can:

- Calculate the period of time between the two moments or between now and any of those moments
- Compare the periods of time between the two moments and other dates
- Perform time operations with a lis of multiple periods
- Generate visualizations of one or more periods of time

Picture of Brent Roose
Name: Brent Roose <contact>
Classes: 1 package by
Country: Belgium Belgium

Details

Complex period comparisons

Latest Version on Packagist Build Status Quality Score StyleCI Total Downloads

This package adds support for comparing multiple dates with each other. You can calculate the overlaps and differences between n-amount of periods, as well as some more basic comparisons between two periods.

Periods can be constructed from any type of DateTime implementation, making this package compatible with custom DateTime implementations like Carbon (see cmixin/enhanced-period to convert directly from and to CarbonPeriod).

Periods are always immutable, there's never the worry about your input dates being changed.

This package is still a work in progress.

Support us

Learn how to create a package like this one, by watching our premium video course:

Laravel Package training

We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.

Installation

You can install the package via composer:

composer require spatie/period

Usage

Quick reference

Creating a period

$period = new Period(
     DateTimeImmutable $start
   , DateTimeImmutable $end
  [, ?int $precisionMask = Precision::DAY]
  [, ?int $boundaryExclusionMask = Boundaries::EXCLUDE_NONE]
)

The static ::make constructor can also take strings and other implementations of DateTimeInterface, as well as an extra format string, in case the textual dates passed aren't of the format Y-m-d or Y-m-d H:i:s.

$period = Period::make(
     string|DateTimeInterface $start
   , string|DateTimeInterface $end
  [, ?int Precision::DAY]
  [, ?int Boundaries::EXCLUDE_NONE]
  [, string $format]
)

Length and boundaries

$period->length(): int

$period->startIncluded(): bool
$period->startExcluded(): bool
$period->endIncluded(): bool
$period->endExcluded(): bool

$period->getStart(): DateTimeImmutable
$period->getStartIncluded(): DateTimeImmutable
$period->getEnd(): DateTimeImmutable
$period->getEndIncluded(): DateTimeImmutable

Comparisons

$period->contains(DateTimeInterface $date): bool
$period->equals(Period $period): bool

$period->overlapsWith(Period $period): bool
$period->touchesWith(Period $period): bool

$period->startsAt(DateTimeInterface $date): bool
$period->startsBefore(DateTimeInterface $date): bool
$period->startsBeforeOrAt(DateTimeInterface $date): bool
$period->startsAfter(DateTimeInterface $date): bool
$period->startsAfterOrAt(DateTimeInterface $date): bool

$period->endsAt(DateTimeInterface $date): bool
$period->endsBefore(DateTimeInterface $date): bool
$period->endsBeforeOrAt(DateTimeInterface $date): bool
$period->endsAfter(DateTimeInterface $date): bool
$period->endsAfterOrAt(DateTimeInterface $date): bool

$period->gap(Period $period): ?Period

$period->overlapSingle(Period $period): ?Period
$period->overlap(Period ...$periods): PeriodCollection
$period->overlapAll(Period ...$periods): Period

$period->diffSingle(Period $period): PeriodCollection
$period->diff(Period ...$periods): PeriodCollection

$periodCollection->overlap(PeriodCollection ...$periodCollections): PeriodCollection
$periodCollection->overlapSingle(PeriodCollection $periodCollection): PeriodCollection
$periodCollection->map(Closure<Period> $closure): PeriodCollection
$periodCollection->filter(Closure<Period> $closure): PeriodCollection
$periodCollection->reduce(Closure<mixed, Period> $closure): mixed

$periodCollection->boundaries(): ?Period

$periodCollection->gaps(): PeriodCollection

Comparing periods

Overlaps with any other period: This method returns a PeriodCollection multiple Period objects representing the overlaps.

/*
 * A       [========]
 * B                    [==]
 * C                            [=====]
 * CURRENT        [===============]
 *
 * OVERLAP        [=]   [==]    [=]
 */
 
$a = Period::make('2018-01-01', '2018-01-31');
$b = Period::make('2018-02-10', '2018-02-20');
$c = Period::make('2018-03-01', '2018-03-31');

$current = Period::make('2018-01-20', '2018-03-10');

$overlaps = $current->overlap($a, $b, $c); 

Overlap with all periods: This method only returns one period where all periods overlap.

/*
 * A              [============]
 * B                   [==]
 * C                  [=======]
 *
 * OVERLAP             [==]
 */

$a = Period::make('2018-01-01', '2018-01-31');
$b = Period::make('2018-01-10', '2018-01-15');
$c = Period::make('2018-01-10', '2018-01-31');

$overlap = $a->overlapAll($b, $c);

Diff between multiple periods: This method returns a PeriodCollection multiple Period objects representing the diffs between several periods and one.

/*
 * A                   [====]
 * B                               [========]
 * C         [=====]
 * CURRENT      [========================]
 *
 * DIFF             [=]      [====]
 */

$a = Period::make('2018-01-05', '2018-01-10');
$b = Period::make('2018-01-15', '2018-03-01');
$c = Period::make('2017-01-01', '2018-01-02');

$current = Period::make('2018-01-01', '2018-01-31');

$diff = $current->diff($a, $b, $c);

Overlaps with: This method returns a boolean indicating of two periods overlap or not.

/*
 * A              [============]
 * B                   [===========]
 */

$a = Period::make('2018-01-01', '2018-01-31');
$b = Period::make('2018-01-10', '2018-02-15');

$overlap = $a->overlapsWith($b); // true

Touches with: This method determines if two periods touch each other.

/*
 * A              [========]
 * B                        [===========]
 */

$a = Period::make('2018-01-01', '2018-01-31');
$b = Period::make('2018-02-01', '2018-02-15');

$overlap = $a->touchesWith($b); // true

Gap: Returns the gap between two periods. If no gap exists, null is returned.

/*
 * A              [========]
 * B                           [===========]
 */

$a = Period::make('2018-01-01', '2018-01-31');
$b = Period::make('2018-02-05', '2018-02-15');

$overlap = $a->gap($b); // Period('2018-02-01', '2018-02-04')

Boundaries of a collection: Get one period representing the boundaries of a collection.

/*
 * A                   [====]
 * B                               [========]
 * C           [=====]
 * D                                             [====]
 *
 * BOUNDARIES  [======================================]
 */
 
$collection = new PeriodCollection(
    Period::make('2018-01-01', '2018-01-05'),
    Period::make('2018-01-10', '2018-01-15'),
    Period::make('2018-01-20', '2018-01-25'),
    Period::make('2018-01-30', '2018-01-31')
);

$boundaries = $collection->boundaries();

Gaps of a collection: Get all the gaps of a collection.

/*
 * A                   [====]
 * B                               [========]
 * C         [=====]
 * D                                             [====]
 *
 * GAPS             [=]      [====]          [==]
 */

$collection = new PeriodCollection(
    Period::make('2018-01-01', '2018-01-05'),
    Period::make('2018-01-10', '2018-01-15'),
    Period::make('2018-01-20', '2018-01-25'),
    Period::make('2018-01-30', '2018-01-31')
);

$gaps = $collection->gaps();

Overlap multiple collections: Returns the overlap between collections. This means an AND operation between collections, and an OR operation within the same collection.

/*
 * A            [=====]      [===========]
 * B            [=================]
 * C                [====================]
 *
 * OVERLAP          [=]      [====]
 */

$a = new PeriodCollection(
    Period::make('2018-01-01', '2018-01-07'),
    Period::make('2018-01-15', '2018-01-25')
);

$b = new PeriodCollection(
    Period::make('2018-01-01', '2018-01-20')
);

$c = new PeriodCollection(
    Period::make('2018-01-06', '2018-01-25')
);

$overlap = $a->overlap($b, $c);

Working with PeriodCollection

Period collections are constructed from several periods:

$collection = new PeriodCollection(
    Period::make('2018-01-01', '2018-01-02'),
    // ?
);

They may be looped over directly and its contents will be recognised by your IDE:

$collection = new PeriodCollection(/?/);

foreach ($collection as $period) {
    $period->?
}

You may destruct them:

[$firstPeriod, $secondPeriod, $thirdPeriod] = $collection;

And finally construct one collection from another:

$newCollection = new PeriodCollection(...$otherCollection);

Precision

Date precision is of utmost importance if you want to reliably compare two periods. The following example:

> Given two periods: [2018-01-01, 2018-01-15] and [2018-01-15, 2018-01-31]; do they overlap?

At first glance the answer is "yes": they overlap on 2018-01-15. But what if the first period ends at 2018-01-15 10:00:00, while the second starts at 2018-01-15 15:00:00? Now they don't anymore!

This is why this package requires you to specify a precision with each period. Only periods with the same precision can be compared.

A more in-depth explanation on why precision is so important can be found here. A period's precision can be specified when constructing that period:

Period::make('2018-01-01', '2018-02-01', Precision::DAY);

The default precision is set on days. These are the available precision options:

Precision::YEAR
Precision::MONTH
Precision::DAY
Precision::HOUR
Precision::MINUTE
Precision::SECOND

Boundaries

By default, period comparisons are done with included boundaries. This means that these two periods overlap:

$a = Period::make('2018-01-01', '2018-02-01');
$b = Period::make('2018-02-01', '2018-02-28');

$a->overlapsWith($b); // true

The length of a period will also include both boundaries:

$a = Period::make('2018-01-01', '2018-01-31');

$a->length(); // 31

It's possible to override the boundary behaviour:

$a = Period::make('2018-01-01', '2018-02-01', null, Boundaries::EXCLUDE_END);
$b = Period::make('2018-02-01', '2018-02-28', null, Boundaries::EXCLUDE_END);

$a->overlapsWith($b); // false

There are four types of boundary exclusion:

Boundaries::EXCLUDE_NONE;
Boundaries::EXCLUDE_START;
Boundaries::EXCLUDE_END;
Boundaries::EXCLUDE_ALL;

Compatibility

You can construct a Period from any type of DateTime object such as Carbon:

Period::make(Carbon::make('2018-01-01'), Carbon::make('2018-01-02'));

Note that as soon as a period is constructed, all further operations on it are immutable. There's never the danger of changing the input dates.

You can iterate a Period like a regular DatePeriod with the precision specified on creation:

$datePeriod = Period::make(Carbon::make('2018-01-01'), Carbon::make('2018-01-31'));

foreach ($datePeriod as $date) {
    / @var DateTimeImmutable $date */
    // 2018-01-01
    // 2018-01-02
    // ...
    // (31 iterations)
}

$timePeriod = Period::make(Carbon::make('2018-01-01 00:00:00'), Carbon::make('2018-01-01 23:59:59'), Precision::HOUR);

foreach ($timePeriod as $time) {
    / @var DateTimeImmutable $time */
    // 2018-01-01 00:00:00
    // 2018-01-01 01:00:00
    // ...
    // (24 iterations)
}

Visualizing periods

You can visualize one or more Period objects as well as PeriodCollection objects to see how they related to one another:

$visualizer = new Visualizer(["width" => 27]);

$visualizer->visualize([
    "A" => Period::make('2018-01-01', '2018-01-31'),
    "B" => Period::make('2018-02-10', '2018-02-20'),
    "C" => Period::make('2018-03-01', '2018-03-31'),
    "D" => Period::make('2018-01-20', '2018-03-10'),
    "OVERLAP" => new PeriodCollection(
        Period::make('2018-01-20', '2018-01-31'),
        Period::make('2018-02-10', '2018-02-20'),
        Period::make('2018-03-01', '2018-03-10')
    ),
]);

And visualize will return the following string:

A          [========]
B                      [==]
C                           [========]
D               [==============]
OVERLAP         [===]  [==] [==]

The visualizer has a configurable width provided upon creation which will control the bounds of the displayed periods:

$visualizer = new Visualizer(["width" => 10]);

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security related issues, please email freek@spatie.be instead of using the issue tracker.

Postcardware

You're free to use this package, but if it makes it to your production environment we highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using.

Our address is: Spatie, Kruikstraat 22, 2018 Antwerp, Belgium.

We publish all received postcards on our company website.

Credits

License

The MIT License (MIT). Please see License File for more information.

  Files folder image Files  
File Role Description
Files folder image.github (1 directory)
Files folder imagesrc (6 files, 1 directory)
Files folder imagetests (6 files)
Accessible without login Plain text file .editorconfig Data Auxiliary data
Accessible without login Plain text file .scrutinizer.yml Data Auxiliary data
Accessible without login Plain text file .styleci.yml Data Auxiliary data
Accessible without login Plain text file CHANGELOG.md Data Auxiliary data
Accessible without login Plain text file composer.json Data Auxiliary data
Accessible without login Plain text file CONTRIBUTING.md Data Auxiliary data
Accessible without login Plain text file LICENSE.md Lic. License text
Accessible without login Plain text file phpunit.xml.dist Data Auxiliary data
Accessible without login Plain text file README.md Doc. Documentation

  Files folder image Files  /  .github  
File Role Description
Files folder imageworkflows (1 file)

  Files folder image Files  /  .github  /  workflows  
File Role Description
  Accessible without login Plain text file run-tests.yml Data Auxiliary data

  Files folder image Files  /  src  
File Role Description
Files folder imageExceptions (3 files)
  Plain text file Boundaries.php Class Class source
  Plain text file IterableImplementation.php Class Class source
  Plain text file Period.php Class Class source
  Plain text file PeriodCollection.php Class Class source
  Plain text file Precision.php Class Class source
  Plain text file Visualizer.php Class Class source

  Files folder image Files  /  src  /  Exceptions  
File Role Description
  Plain text file CannotComparePeriods.php Class Class source
  Plain text file InvalidDate.php Class Class source
  Plain text file InvalidPeriod.php Class Class source

  Files folder image Files  /  tests  
File Role Description
  Plain text file BoundaryTest.php Class Class source
  Plain text file DateTimeExtensionTest.php Class Class source
  Plain text file PeriodCollectionTest.php Class Class source
  Plain text file PeriodTest.php Class Class source
  Plain text file PrecisionTest.php Class Class source
  Plain text file VisualizerTest.php Class Class source

 Version Control Unique User Downloads  
 100%
Total:0
This week:0

For more information send a message to info at phpclasses dot org.