Overview
Period
is PHP’s missing time range API. Based on ideas from Resolving Feature Envy in the Domain by Mathias Verraes, this package extends the concept to cover all basic operations regarding time ranges.
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')
Period::INCLUDE_START_EXCLUDE_END
);
$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 named constructors and helper classes.
Comparing intervals
$period = Period::after('2014-01-01', '1 MONTH', Period::INCLUDE_ALL);
$altPeriod = Period::after('2014-01-01', '1 MONTH', Period::EXCLUDE_ALL);
$period->durationEquals($altPeriod), //returns true
$period->equals($altPeriod), //returns false
$period->contains($altPeriod), //returns true
$altPeriod->contains($period), //return false
$period->contains('2014-01-10'), //returns true
Datepoint::create('2014-02-10')->isDuring($period) //returns false
The class comes with other ways to compare time ranges based on their duration and/or their datepoints.
Datepoint
extends DateTimeImmutable
and offers more methods.
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->gaps(); // a new Sequence object
count($gaps); // 2
Sequence
is a Period
container and collection. The class has more methods.