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.

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.

use function League\Period\month;

foreach (month(2014, 10)->getDatePeriod('1 DAY') as $day) {

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

Comparing intervals

use function League\Period\interval_after;
use function League\Period\iso_week;

$interval = interval_after('2014-01-01', '1 WEEK');
$alt_interval = iso_week(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

use function League\Period\interval_after;

$period = interval_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.