Period

Overview

Author Latest Version Software License Build Status Total Downloads

Period is PHP’s missing time range API. It is based on Resolving Feature Envy in the Domain by Mathias Verraes and extends the concept to cover all basic operations regarding interval.

In your code, you will always have to typehint against the League\Period\Period class directly because it is a immutable value object class marked as final and the library does not provide an interface.

Since version 4.1 a League\Period\Sequence class is added to improve manipulating a collection of Period objects.

Accessing the interval properties

use League\Period\Period;

$interval = new Period(
    new DateTime('2014-10-03 08:12:37'),
    new DateTimeImmutable('2014-10-03 08:12:37')
);
$start = $interval->getStartDate(); //returns a DateTimeImmutable
$end = $interval->getEndDate();     //returns a DateTimeImmutable
$duration = $interval->getDateInterval();       //returns a DateInterval object
$duration2 = $interval->getTimestampInterval(); //returns the duration in seconds
echo $interval; //displays '2014-10-03T08:12:37Z/2014-10-03T09:12:37Z'

Learn more about how this all works in the basic usage.

Iterate over the interval

A simple example on how to get all the days from a selected month.

foreach (Period::fromMonth(2014, 10)->getDatePeriod('1 DAY') as $day) {
    $day->format('Y-m-d');
}

To help easily instantiate your time range and manipulating it, the package comes bundle with helper functions.

Comparing intervals

$interval = Period::after('2014-01-01', '1 WEEK');
$alt_interval = Period::fromIsoWeek(2014, 1);
$interval->durationEquals($alt_interval); //returns true
$interval->equals($alt_interval);         //returns false

The class comes with other ways to compare time ranges based on their duration and/or their datepoints.

Modifying interval

$period = Period::after('2014-01-01', '1 WEEK');
$altPeriod = $period->endingOn('2014-02-03');
$period->contains($altPeriod); //return false;
$altPeriod->durationGreaterThan($period); //return true;

Period is an immutable value object. Any changes to the object returns a new object. The class has more modifying methods.

Accessing all gaps between intervals

$sequence = new Sequence(
    new Period('2018-01-01', '2018-01-31'),
    new Period('2017-01-01', '2017-01-31'),
    new Period('2020-01-01', '2020-01-31')
);
$gaps = $sequence->getGaps(); // a new Sequence object
count($gaps); // 2

Sequence is a Period container and collection. The class has more methods.