Period

The Duration class

The Duration class is introduced in version 4.2.

A duration is the continuous portion of time between two datepoints expressed as a DateInterval object. The duration cannot be negative.

The Duration class is introduced to ease duration manipulation. This class extends PHP’s DateInterval class.

Constructors

Duration::create

Since version 4.5 chronometer format is supported.

public Duration::create($duration): self

Converts its single input into a Duration object or throws a TypeError otherwise.

parameter

$duration can be:

WARNING: When the string is not parsable by DateInterval::createFromDateString a DateInterval object representing the 0 interval is returned as described in PHP bug #50020.

Examples

use League\Period\Duration;
use League\Period\Period;

Duration::create('1 DAY');                  // returns new Duration('P1D')
Duration::create(2018);                     // returns new Duration('PT2018S')
Duration::create(new DateInterval('PT1H')); // returns new Duration('PT1H')
Duration::create('12:30');                  // returns new Duration('PT12M30S')  
Duration::create(new Period('now', 'tomorrow'));
// returns (new DateTime('yesterday'))->diff(new DateTime('tomorrow'))

Default constructor

The constructor supports fraction on the smallest value.

For instance, the following is works while throwing an Exception on DateInterval.

use League\Period\Duration;

$duration = new Duration('PT5M0.5S');
$duration->f; //0.5;

new DateInterval('PT5M0.5S'); // will throw an Exception

Duration representations

String representation

Deprecated since version 4.5. You should use Duration::format instead.

public Duration::__toString(void): string

Returns the string representation of a Duration object using ISO8601 time interval representation.

$duration = new Duration('PT5M0.5S');
echo $duration; // 'PT5M0.5S'

As per the specification the smallest value (ie the second) can accept a decimal fraction.

Duration mutation method

Adjusting duration according to a datepoint

Since version 4.6

Replaces and deprecates the withoutCarryOver method introduced in version 4.5.

public Duration::adjustedTo($reference_date): self

Returns a new instance with recalculate duration according to the given datepoint. If the recalculate interval does not change the current object then it is returned as is, otherwise a new object is returned.

The reference datepoint can be any valid vaue accepted by the Datepoint::create named constructor.

$duration = Duration::create('29 days');
echo $duration; // 'P29D'
echo $duration->adjustedTo('2019-02-01'); // 'P1M1D' using a non leap year
echo $duration->adjustedTo('2020-02-01'); // 'P1M'   using a leap year

The returned object depends on the date time and timezone or the $reference_date